When you pass add_subtract()
as an argument, you're calling the function and then passing the return value as the argument. In this case you want to pass the function itself... try it without the parens.
segmentation fault on random running instances
-
30-05-2022 - |
Question
Below program gives me segmentation fault(core dumped) error on random instances. sometimes it runs without any error. The program is just for understanding deadlocks.
Even though I have run this program for about 15 times, I haven't faced a deadlock so far. Sometimes the program runs smoothly(which can be expected) and sometimes it gives the segmentation fault(which is not expected). Why do I get the segmentation fault?
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
int a=5;
int b=3;
pthread_mutex_t mutex1,mutex2;
void* add_subtract(){
pthread_mutex_lock(&mutex1);
pthread_mutex_lock(&mutex2);
a=a+2;
b=b-2;
printf("%d %d\n",a,b);
pthread_mutex_unlock(&mutex2);
pthread_mutex_unlock(&mutex1);
}
void* subtract_add(){
pthread_mutex_lock(&mutex2);
pthread_mutex_lock(&mutex1);
b=b-2;
a=a+2;
printf("%d %d\n",a,b);
pthread_mutex_unlock(&mutex1);
pthread_mutex_unlock(&mutex2);
}
int main(){
pthread_t thread1,thread2;
pthread_create(&thread1,NULL,add_subtract(),NULL);
pthread_create(&thread2,NULL,subtract_add(),NULL);
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
return 0;
}
Solution
OTHER TIPS
I think you need to initialize the mutex: http://pubs.opengroup.org/onlinepubs/7908799/xsh/pthread_mutex_init.html
The pthread_mutex_init() function initialises the mutex referenced by mutex with attributes specified by attr. If attr is NULL, the default mutex attributes are used; the effect is the same as passing the address of a default mutex attributes object. Upon successful initialisation, the state of the mutex becomes initialised and unlocked.