我有一个创建大量线程的 C++ 应用程序。使用 ulimit -v unlimited,应用程序在创建 1080 个线程后因段错误而崩溃。当我试图访问分配有"new"的内存时发生崩溃。 “new”返回非空指针,但访问它会出现段错误。 使用 ulimit -v 500000,应用程序不会崩溃,但会限制最大线程数(pthread_create 失败 - 更好的行为)。 根据 top,当总内存达到物理 RAM 大小时,应用程序崩溃(ulimit -v unlimited)。 我需要大约 1500 个线程(我知道缺点……) 线程很小,根据valgrind,每个线程使用~16kb的堆栈,所以我不知道为什么应用程序占用了这么多内存。 我可以更改/检查什么以减少每线程内存? ulimit -s 1024 没有帮助。
最佳答案
new
返回非空指针但在访问该内存时崩溃的问题是 Linux 内存过度使用“功能”。 man malloc
:
By default, Linux follows an optimistic memory allocation strategy. This means that when
malloc()
returns non-NULL there is no guarantee that the memory really is available. In case it turns out that the system is out of memory, one or more processes will be killed by the OOM killer. For more information, see the description of/proc/sys/vm/overcommit_memory
and/proc/sys/vm/oom_adj
inproc(5)
, and the Linux kernel source fileDocumentation/vm/overcommit-accounting
.
On Linux/x86-32, the default stack size for a new thread is 2 megabytes. Under the NPTL threading implementation, if the
RLIMIT_STACK
soft resource limit at the time the program started has any value other than "unlimited", then it determines the default stack size of new threads. Usingpthread_attr_setstacksize(3)
, the stack size attribute can be explicitly set in the attr argument used to create a thread, in order to obtain a stack size other than the default.
关于c++ - 减少 Linux 中的每个线程内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44326189/