c++ - 减少 Linux 中的每个线程内存

标签 c++ linux multithreading memory

我有一个创建大量线程的 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 in proc(5), and the Linux kernel source file Documentation/vm/overcommit-accounting.


man pthread_create :

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. Using pthread_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/

相关文章:

c++ - 在函数内释放动态内存

C++ 文本文件 I/O

linux - 在 bash 脚本中执行 cut 命令

linux - 如何将命令应用到第n列?

c++ - 如何处理连接到 CPP 中服务器的多个客户端?

c++ - 条件变量中的 gcc 错误::wait_for

c++ - 预加载运算符删除释放大小

java - Linux下OpenCV 2.8.4安装进行Java开发

C# 在新线程或任务中打开表单?

java - 如何在多实例 Tomcat 环境中以固定间隔运行任务?