简体   繁体   中英

Why there is deadlock while using mutex in pthread?

Pthread program given below demonstrate the mutex example in pthread. But while running this code deadlock is occurring for most of the time giving right result for some runs.

#include<pthread.h>
#include<stdio.h>
#include<unistd.h>
volatile int sv=10;
volatile int x,y,temp=10;
pthread_mutex_t mut;
pthread_cond_t con;
void *ChildThread(void *arg)
{
pthread_mutex_lock (&mut);
pthread_cond_wait(&con, &mut);  
x=sv;
x++;
sv=x;
printf("The child sv is %d\n",sv);
pthread_mutex_unlock (&mut);
pthread_exit(NULL);
}

void *ChildThread2(void *arg)
{
pthread_mutex_lock (&mut);
y=sv;
y--;
sv=y;
printf("The child2 sv is %d\n",sv); 
pthread_cond_signal(&con);
pthread_mutex_unlock (&mut);
pthread_exit(NULL);
}

int main(void)
{
pthread_t child1,child2,child3;
pthread_mutex_init(&mut, NULL);
pthread_create(&child2,NULL,ChildThread2,NULL);
pthread_create(&child1,NULL,ChildThread,NULL);
pthread_cond_destroy(&con);
pthread_mutex_destroy(&mut);
pthread_join(child1,NULL);
pthread_join(child2,NULL);
return 0;
}

Your deadlock here is likely caused by misuse of pthread_cond_wait() . You typically want to call pthread_cond_wait() in a loop, checking a condition, eg.

while (!cond)
    pthread_cond_wait(...);

As pthread_cond_signal() will only wake a thread sleeping on pthread_cond_wait() at that time, if the signalling thread runs first, the waiter will never wake up.

Other problems here are that you're destroying your condition variable and mutex before the threads are done, which generally leads to unexpected behavior. You should pthread_join() the threads before taking away their resources. You also never initialize the condition variable.

One issue is that you never initialize the condition variable. Another is that you destroy the mutex (and try to destroy the uninitialized condition variable) while the threads that use them could still be running.

There is no need to initialize static mutexes or conditions dynamically with the init functions, nor to destroy them at the end. Use PTHREAD_MUTEX_INITIALIZER and PTHREAD_COND_INITIALIZER at the definition of your variables mut and cond :

pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t con = PTHREAD_COND_INITIALIZER;

And then erase all calls to _init and _destroy functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM