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:
You are dereferencing a NULL pointer here:
*s = *((int *)arg0) * 1000000;
Since you define
int *s = 0;
globally. You probably wanted to define it asint s = 0;
and then uses
everywhere instead of*s
.As noted by Rainer Keller in the comments, you are not initializing your
mutex
. You should either initialize it statically toPTHREAD_MUTEX_INITIALIZER
, or at runtime inmain
withpthread_mutex_init(&mutex)
.