Segfault в pthread_join (только иногда)

Я хочу использовать кучу pthreads в моем приложении. Чтобы ознакомиться с библиотекой pthread, я начал с небольшого демонстрационного приложения (см. Прилагаемый исходный код).

Если я создаю 200 потоков, все работает хорошо. Однако, если я увеличу количество потоков до 2000, приложение завершится с ошибкой. Согласно gdb, segfault происходит в 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; 
}

0 ответов

Другие вопросы по тегам