Pthreads - 内存不足?
我正在用 C 编写一些在 Linux 中创建大量 Pthread 的程序。
当我使用少量线程运行该程序时,它可以工作,但是一旦我让它创建大约 1000 个线程,它就会出现错误。现在 errno 标志已设置,但我想知道是哪一个问题导致的。 EAGAIN
、EINVAL
、ELEMULTITHREADFORK
或 ENOMEM
。
有什么方法可以查明这是否是这些错误之一,如果是,那么它是哪一个?
I am programming something in C that creates a lot of Pthreads in Linux.
When I run the program with a low amount of threads it works, but once I make it create around 1000 threads it gives errors. Now the errno
flag is set, but I want to know which one of the problems caused it. EAGAIN
, EINVAL
, ELEMULTITHREADFORK
, or ENOMEM
.
Is there any way that I can find out if it is one of these errors, and, if yes, which one it is?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我相信您正在寻找的是
pthread_attr_setstacksize
函数。默认情况下,glibc 为每个线程的堆栈保留 2MB、8MB 或 10MB 或内存。按照这个速度,您将很快耗尽 32 位计算机上的虚拟地址空间,甚至在 64 位计算机上也很快耗尽提交费用。这段代码过于简单;当然,您可能想要检查其中一些调用是否失败。其实你的问题本来就是这个意思。
pthread_*
函数几乎都返回错误代码作为其返回值,而不是在errno
中,因此errno
不能用于检查结果,除非将返回值分配给errno
,否则perror
将不起作用。相反,做类似的事情:I believe what you're looking for is the
pthread_attr_setstacksize
function. By default, glibc reserves 2MB, 8MB, or 10MB or memory for each thread's stack. At this rate you'll quickly exhaust the virtual address space on a 32-bit machine, and quickly exhaust the commit charge even on 64-bit machines.This code is over-simplified; naturally you may want to check for failure on some of these calls. Actually that's what your question was originally about.
pthread_*
functions almost all return the error code as their return value rather than inerrno
, soerrno
cannot be used to inspect the result, andperror
will not work unless you assign the return value toerrno
. Instead, do something like:perror()
应该可以解决问题。在 Linux 系统上执行
man 3 perror
。perror()
should do the trick.Do
man 3 perror
on your linux system.仅用于俗气的测试:
R 是正确的,默认堆栈大小将消耗那么多线程的内存。
Just for cheesy testing:
R is correct that the default stack size is going to chew up memory with that many threads.