一句话总结:pthread_cond_signal仅给一个线程发信号让其脱离阻塞状态继续运行,pthread_cond_wait的流程是lock(调用前先将信号量加锁)-->unlock-->wait()return-->lock。
1、使用pthread_cond_signal最多只给一个线程发信号。假如有多个线程正在阻塞等待着这个条件变量的话,那么是根据各等待线程优先级的高低确定哪个线程接收到信号开始继续执行。如果各线程优先级相同,则根据等待时间的长短来确定哪个线程获得信号。但无论如何pthread_cond_signal调用一次最多发信号一次。如果没有其他进程阻塞那么也成功返回。
而pthread_cond_broadcast()则激活所有等待线程。
2、pthread_cond_wait:条件变量是利用线程间共享的全局变量进行同步的一种机制,主要包括两个动作:一个线程等待"条件变量的条件成立"而挂起;另一个线程使"条件成立"(给出条件成立信号)。为了防止竞争,条件变量的使用总是和一个互斥锁结合在一起。
#include
#include
#include
using namespacestd;
pthread_mutex_t g_mutex =PTHREAD_MUTEX_INITIALIZER;//初始化互斥锁
pthread_cond_t g_cond =PTHREAD_COND_INITIALIZER; //初始化条件变量
uint g_cnt = 0;
void *thread1(void* arg)
{
while (g_cnt <=4) {
pthread_mutex_lock(&g_mutex); //锁住互斥量
cout<<"thread1:lock "<<__LINE__<<endl;
if (0 ==g_cnt%2) {
cout<<"thread1:send signal start... "<<endl;
pthread_cond_signal(&g_cond);//发送一个信号给另外一个正在处于阻塞等待状态的线程,使其脱离阻塞状态,继续执行
cout<<"thread1:send signal end... "<<endl;
sleep(1);
}
pthread_mutex_unlock(&g_mutex);
cout<<"thread1:unlock "<<endl;
sleep(1);
++g_cnt;
}
returnNULL;
}
void *thread2(void* arg)
{
while (g_cnt <=4) {
pthread_mutex_lock(&g_mutex); //锁住互斥量
cout<<"thread2:lock "<<__LINE__<<endl;
if (1 ==g_cnt%2) {
cout<<"thread2:wait signal start... "<<endl;
pthread_cond_wait(&g_cond, &g_mutex); //流程是:lock-->unlock-->wait()return-->lock
cout<<"thread2:wait signal end... "<<endl;
}
pthread_mutex_unlock(&g_mutex);
cout<<"thread2:unlock "<<endl;
sleep(1);
}
returnNULL;
}
int main(int argc,constchar * argv[]) {
// insert code here...
pthread_t t1;
pthread_t t2;
pthread_create(&t1,NULL,thread1,NULL);
pthread_create(&t2,NULL,thread2,NULL);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
pthread_mutex_destroy(&g_mutex);
pthread_cond_destroy(&g_cond);
exit(0);
return0;
}
thread2:lock 41
thread2:wait signal start...
thread1:lock 22
thread1:send signal start...
thread1:send signal end...
thread1:unlock
thread2:wait signal end...
thread2:unlock