Jomana
Jomana

Reputation: 27

C pthread segmentation fault when running many threads

The following code is running without any problems if I keep nThreads under 300, but if I enter 400 for example, then I get a segmentation fault. I think this has to do with maximum number of threads, but I am not sure how to allow more threads, or at least how to determine the maximum number of threads I can run. any idea? thanks in advance

#include <stdlib.h>
#include <pthread.h>
#include <malloc.h>
#include <unistd.h>

void* thread(void* arg);

int counter=0;
pthread_mutex_t counterMutex = PTHREAD_MUTEX_INITIALIZER;

int main(){
    int nThreads = 0;
    printf("How many threads? ");
    scanf("%d", &nThreads);
    pthread_t* threads = (pthread_t*)malloc(nThreads*sizeof(pthread_t));

    for(int i=0; i < nThreads; i++){
        pthread_create(&threads[i], NULL, thread, (void*)&i);
    }
    for(int i=0; i < nThreads; i++){
       pthread_join(threads[i], NULL);
    }
    printf("counter is %d\n\n", counter);
    exit(0);
}

void* thread(void* arg){
    pthread_mutex_lock(&counterMutex);
    counter++;
    printf("thread %d, counter is %d\n\n", *(int*)arg, counter);
    pthread_mutex_unlock(&counterMutex);
    pthread_exit(NULL);
}

Upvotes: 2

Views: 4634

Answers (4)

Ed Heal
Ed Heal

Reputation: 59987

pthread_mutex_init would not go amiss! And try for the error conditions

Upvotes: 0

GreenScape
GreenScape

Reputation: 7717

Why do you even need 400 threads? Do you realise that having that huge number of threads which are additionally synchronised will slow down your program incredibly?

Upvotes: 0

Mahmoud Al-Qudsi
Mahmoud Al-Qudsi

Reputation: 29519

You're doing something wrong if you're creating that many threads unless you're on a supercomputer. The 1990s method was to create a thread for each "state" (connection, task, etc.) but the current (and correct) approach is to create only as many threads as CPUs/Cores (give or take), and then use asynchronous events to pull off the rest.

Upvotes: 1

David Schwartz
David Schwartz

Reputation: 182743

You don't check if pthread_create succeeded or failed. If it fails, you wind up calling pthread_join with an invalid pthread_t.

Upvotes: 5

Related Questions