Home > Blockchain >  pthread and mutex_lock throwing segmentation core dumped
pthread and mutex_lock throwing segmentation core dumped

Time:12-14

I am trying to play with threads using a mutex for syncronization, but it seems that my code throws a "segmentation fault core dumped" error every time after compiling it.

#include <pthread.h>
#include <stdio.h>

pthread_mutex_t mutex;
int *s = 0;
void *fonction(void * arg0) {
    pthread_mutex_lock( & mutex);
    *s  = *((int *)arg0) * 1000000;
    pthread_mutex_unlock(&mutex);

}
int main() {
    pthread_t thread[5];
    int ordre[5];
    for (int i = 0; i < 5; i  )
        ordre[i] = i;
    for (int i = 0; i < 5; i  )
        pthread_create(&thread[i], NULL, fonction, & ordre[i]);
    for (int i = 0; i < 5; i  )
        pthread_join(thread[i], NULL);

    printf("%d\n", * s);

    return 0;

}

CodePudding user response:

Two things:

  1. You are dereferencing a NULL pointer here:

    *s  = *((int *)arg0) * 1000000;
    

    Since you define int *s = 0; globally. You probably wanted to define it as int s = 0; and then use s everywhere instead of *s.

  2. As noted by Rainer Keller in the comments, you are not initializing your mutex. You should either initialize it statically to PTHREAD_MUTEX_INITIALIZER, or at runtime in main with pthread_mutex_init(&mutex).

  • Related