I want to use a bunch of pthreads in my application. To get familiar with the pthread library, I started with a small demo application (see attached sourcecode).
If I create 200 threads, all works well. However, if I increase the number of threads to 2000 the application crashes with a segfault. According to gdb the segfault happens at pthread_join. Unfortunately I could'nt figure out why this is happening.
First, I thought, that my linux machine could'nt handle that many threads, so I increased the value in /proc/sys/kernel/threads-max
, but that didn't change anything.
What am I doing wrong?
#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;
}