我正在尝试运行一个简单的多线程编程,但我从 gcc 收到此错误
pthread_create() 的返回码是 11
我该如何解决这个问题?
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 20000
void *PrintHello(void *threadid)
{
long tid;
tid = (long)threadid;
printf("Hello World! It's me, thread #%ld!\n", tid);
pthread_exit(NULL);
}
int main (int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
int rc;
long t;
for(t=0; t<NUM_THREADS; t++){
printf("In main: creating thread %ld\n", t);
rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
/* Last thing that main() should do */
pthread_exit(NULL);
}
好吧,您可以首先确定错误的实际含义。根据this http://www.barricane.com/c-error-codes-include-errno and this http://pubs.opengroup.org/onlinepubs/7908799/xsh/pthread_create.html(其他资源会告诉你相同的信息,这只是一个例子),数字11代表EAGAIN
这又意味着“系统缺乏创建另一个线程所需的资源,或者将超出系统对进程中线程总数 PTHREAD_THREADS_MAX 施加的限制。”。
这与您尝试创建 20.000(!) 个线程的事实相符。创建更少的线程,或者等到线程完成后再启动新线程。
请注意,可以创建的最大线程数取决于您的系统(甚至可能取决于许多其他设置)。如果您确实需要知道,请谷歌搜索“如何查找 PTHREAD_THREADS_MAX”。
然而,除非这只是一个简单的例子(或者甚至是这样),否则你可能想研究一下这个概念线程池和队列 http://en.wikipedia.org/wiki/Thread_pool_pattern.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)