【问题标题】:Return code from pthread_create() is 11pthread_create() 的返回码是 11
【发布时间】:2011-08-12 10:06:41
【问题描述】:

我正在尝试运行一个简单的多线程编程,但我从 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);                          
}                           

【问题讨论】:

  • 20000个线程要做什么?你在集群上吗?
  • 您应该更改默认线程堆栈大小以启动大量线程。
  • osgx 说了什么。见pthread_attr_setstacksize
  • @RedX 测试,我正在学习多线程编程,并试图弄清楚整个系统的速度。

标签: c multithreading gcc


【解决方案1】:

好吧,您可以从确定错误的实际含义开始。根据thisthis(其他资源会告诉你相同的信息,这只是一个例子),数字11代表EAGAIN,这反过来意味着“系统缺乏创建另一个线程所需的资源,否则将超出系统对进程中线程总数的限制 PTHREAD_THREADS_MAX。"。

这与您尝试创建 20.000(!) 个线程的事实相符。创建更少的线程,或者等到线程完成后再开始新的线程。

请注意,可以创建的最大线程数取决于您的系统(甚至可能取决于许多其他设置)。如果您真的需要知道,请在 Google 上搜索“如何查找 PTHREAD_THREADS_MAX”。

但是,除非这只是一个玩弄(或什至可能)的琐碎示例,否则您可能需要研究thread pools and queues 的概念。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-31
  • 2021-09-14
相关资源
最近更新 更多