Your call to pthread_cond_wait()
is fine, so the problem must be elsewhere. You have three bugs that I can see:
Firstly, in main()
you are only initialising the first condition variable in the array. You need to initialise all N
condition variables:
for(int i = 0; i < N; i++) {
fork[i] = true;
pthread_cond_init(&cond[i], NULL);
}
pthread_mutex_init(&mon, NULL);
Secondly, in put_fork()
you have an incorrect calculation for one of the condition variables to signal:
pthread_cond_signal(cond + (id-1)%N); /* incorrect */
When id
is equal to zero, (id - 1) % N
is equal to -1, so this will try to signal cond - 1
, which does not point at a condition variable (it's possible that this pointer actually corrupts your mutex, since it might well be placed directly before cond
on the stack). The calculation you actually want is:
pthread_cond_signal(cond + (id + N - 1) % N);
The third bug isn't the cause of your deadlock, but you shouldn't call srand(time(NULL))
every time you call rand()
- just call that once, at the start of main()
.