开发者

Pthreads - out of memory?

I am programming something in C that creates a lot of Pthreads in Linux.

When I run the program with a low amoun开发者_StackOverflow社区t 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?


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.

pthread_t td;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setstacksize(&attr, 32768);
pthread_create(&td, &attr, start_function, start_art);
pthread_attr_destroy(&attr);

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 in errno, so errno cannot be used to inspect the result, and perror will not work unless you assign the return value to errno. Instead, do something like:

result = pthread_create(&td, &attr, start_function, start_art);
switch (result) {
case EINVAL: /* ... */
case EAGAIN: /* ... */
/* etc. */
}


perror() should do the trick.

Do man 3 perror on your linux system.


Just for cheesy testing:

int ret;
pthread_t tid;

if ((ret = pthread_create(&tid, NULL, startfunc, NULL)) != 0)
{
    errno = ret;
    perror("pthread_create");
}

R is correct that the default stack size is going to chew up memory with that many threads.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜