我想在我的应用程序中使用一堆 pthread。为了熟悉 pthread 库,我从一个小型演示应用程序开始(参见随附的源代码)。
如果我创建 200 个线程,一切正常。但是,如果我将线程数增加到 2000,应用程序会因段错误而崩溃。根据gdb,段错误发生在pthread_join。不幸的是,我无法弄清楚为什么会这样。
首先,我认为我的 linux 机器无法处理那么多线程,所以我增加了 中的值/proc/sys/kernel/threads-max
,但这并没有改变任何东西。
我究竟做错了什么?
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define THREADS 200 //If I increase this value to 2000, the application crashes with a segfault
struct tInfo_t{
int sockfd;
};
pthread_t workerThreads[THREADS];
struct tInfo_t tInfo[THREADS];
void *handle(void *arg){
struct tInfo_t threadArgs = *((struct tInfo_t*)arg);
pthread_exit(0); //do nothing, just exit
return NULL; //to make the compiler happy
}
int main(int argc, char *argv[])
{
int i = 0;
//create a few threads
for(i = 0; i < THREADS; i++){
if(pthread_create(&workerThreads[i], 0, handle, (void*)&tInfo[i]) == -1){
printf("couldn't create thread. %d \n", workerThreads[i]);
return EXIT_FAILURE;
}
printf("Thread #%d spawned\n", i);
}
//wait until all threads finished their job
for(i = 0; i < THREADS; i++){
pthread_join(workerThreads[j], NULL);
}
return EXIT_SUCCESS;
}