当前位置: 技术问答>linux和unix
关于互斥锁的问题,请高手给于指点
来源: 互联网 发布时间:2015-12-19
本文导语: pthread_mutex_t count_lock; pthread_cond_t count_nonzero; unsigned count; decrement_count () { pthread_mutex_lock (&count_lock); while(count==0) pthread_cond_wait( &count_nonzero, &count_lock); count=count -1; pthread_mutex_unlock (&count_lock); } increment_count(){ pthr...
pthread_mutex_t count_lock;
pthread_cond_t count_nonzero;
unsigned count;
decrement_count () {
pthread_mutex_lock (&count_lock);
while(count==0)
pthread_cond_wait( &count_nonzero, &count_lock);
count=count -1;
pthread_mutex_unlock (&count_lock);
}
increment_count(){
pthread_mutex_lock(&count_lock);
if(count==0)
pthread_cond_signal(&count_nonzero);
count=count+1;
pthread_mutex_unlock(&count_lock);
}
count值为0时,decrement函数在pthread_cond_wait处被阻塞,并打开互斥锁count_lock。此时,当调用到函数increment_count时,pthread_cond_signal()函数改变条件变量,告知decrement_count()停止阻塞。但是在decrement_count()最后一句又打开了互斥锁count_lock,pthread_cond_wait()不是已经打开了互斥锁了吗?我不太明白.
pthread_cond_t count_nonzero;
unsigned count;
decrement_count () {
pthread_mutex_lock (&count_lock);
while(count==0)
pthread_cond_wait( &count_nonzero, &count_lock);
count=count -1;
pthread_mutex_unlock (&count_lock);
}
increment_count(){
pthread_mutex_lock(&count_lock);
if(count==0)
pthread_cond_signal(&count_nonzero);
count=count+1;
pthread_mutex_unlock(&count_lock);
}
count值为0时,decrement函数在pthread_cond_wait处被阻塞,并打开互斥锁count_lock。此时,当调用到函数increment_count时,pthread_cond_signal()函数改变条件变量,告知decrement_count()停止阻塞。但是在decrement_count()最后一句又打开了互斥锁count_lock,pthread_cond_wait()不是已经打开了互斥锁了吗?我不太明白.
|
pthread_cond_wait 函数原子的执行以下两个操作:
1, 给互斥锁解锁
2, 把调用线程投入睡眠直到另外某个线程调用pthread_cond_signal函数.
pthread_cond_wait返回前重新给互斥锁加锁.
1,当count!=0的时候不满足while的条件,所以不会调用pthread_cond_wait,所以在while前加的锁还没有被解开,这时候调用pthread_mutex_unlock (&count_lock);来解while前的锁.
2,当调用了pthread_cond_singal函数, pthread_cond_wait重新加锁后返回,继续执行while,如果这时候count!=0, 退出循环,这时候锁还没有解开,需要pthread_mutex_unlock (&count_lock);来解
1, 给互斥锁解锁
2, 把调用线程投入睡眠直到另外某个线程调用pthread_cond_signal函数.
pthread_cond_wait返回前重新给互斥锁加锁.
1,当count!=0的时候不满足while的条件,所以不会调用pthread_cond_wait,所以在while前加的锁还没有被解开,这时候调用pthread_mutex_unlock (&count_lock);来解while前的锁.
2,当调用了pthread_cond_singal函数, pthread_cond_wait重新加锁后返回,继续执行while,如果这时候count!=0, 退出循环,这时候锁还没有解开,需要pthread_mutex_unlock (&count_lock);来解