Linux線程同步之條件變量
條件變量是線程可用的另一種同步機(jī)制。條件變量給多個線程提供了一個會合的場所。條件本身是由互斥量保護(hù)的。線程在改變 條件狀態(tài)前必須首先鎖住互斥量。
條件變量的初始化 pthread_cond_init
去除初始化 pthread_cond_destroy
等待 pthread_cond_wait
滿足條件給向進(jìn)程發(fā)送信號 pthread_cond_signal
下面程序展示了利用條件變量等待另外兩個線程滿足條件時,第三個進(jìn)程繼續(xù)向前執(zhí)行
#include <stdio.h> #include <pthread.h> #include <signal.h> pthread_mutex_t m1, m2; pthread_cond_t c1,c2; pthread_t t1, t2, t3; void* r1(void *arg) { sleep(10); //睡眠10秒 pthread_cond_signal(&c1); printf("t1 finish\n"); while(1); } void* r2(void *arg) { sleep(15);//睡眠15秒 pthread_cond_signal(&c2); printf("t2 finish\n"); while(1); } void* r3(void *arg) { pthread_cond_wait(&c1, &m1); pthread_cond_wait(&c2, &m2); printf("finish\n");//15秒后線程打印 } main() { pthread_mutex_init(&m1, 0); pthread_mutex_init(&m2, 0); pthread_cond_init(&c1, 0); pthread_cond_init(&c2, 0); pthread_create(&t1, 0, r1, 0); pthread_create(&t2, 0, r2, 0); pthread_create(&t3, 0, r3, 0); while(1); } |
執(zhí)行結(jié)果
條件變量與互斥量一起使用時,允許線程以無競爭的方式等待特定的條件發(fā)生。
下面程序中,由于在互斥量中等待條件會造成死鎖
#include <pthread.h> #include <stdio.h> #include <signal.h> pthread_t t1,t2; pthread_mutex_t m1,m2; pthread_cond_t c; void *r1(void *d) { while(1) { pthread_mutex_lock(&m1); printf("wait\n"); pthread_cond_wait(&c,&m2); pthread_mutex_unlock(&m1); } } void *r2(void *d) { while(1) { pthread_mutex_lock(&m1); printf("signal\n"); pthread_cond_signal(&c); pthread_mutex_unlock(&m1); } } main() { pthread_cond_init(&c,0); pthread_mutex_init(&m1,0); pthread_mutex_init(&m2,0); pthread_create(&t1,0,r1,0); pthread_create(&t2,0,r2,0); while(1); /* pthread_join(t1,0); pthread_join(t2,0); pthread_mutex_destroy(&m2); pthread_mutex_destroy(&m1); pthread_cond_destroy(&c);*/ } |
執(zhí)行結(jié)果,程序執(zhí)行到某一時刻發(fā)生死鎖,不再向下執(zhí)行
改進(jìn)后的程序,允許線程以無競爭的方式等待,不會發(fā)生死鎖
#include <pthread.h> #include <stdio.h> #include <signal.h> pthread_t t1,t2; pthread_mutex_t m1,m2; pthread_cond_t c; void *r1(void *d) { while(1) { pthread_mutex_lock(&m1); printf("wait\n"); pthread_cond_wait(&c,&m1); pthread_mutex_unlock(&m1); } } void *r2(void *d) { while(1) { pthread_mutex_lock(&m1); printf("signal\n"); pthread_cond_signal(&c); pthread_mutex_unlock(&m1); } } main() { pthread_cond_init(&c,0); pthread_mutex_init(&m1,0); pthread_mutex_init(&m2,0); pthread_create(&t1,0,r1,0); pthread_create(&t2,0,r2,0); while(1); /* pthread_join(t1,0); pthread_join(t2,0); pthread_mutex_destroy(&m2); pthread_mutex_destroy(&m1); pthread_cond_destroy(&c);*/ } |
posted on 2014-02-28 11:01 順其自然EVO 閱讀(383) 評論(0) 編輯 收藏 所屬分類: linux