转载:https://blog.csdn.net/afootball/article/details/107937516
pthread_cond_signal——唤醒睡眠的线程,一次只能唤醒一个线程
pthread_cond_broadcast——唤醒睡眠的线程,一次唤醒所有睡眠的线程
理解:
- pthread_cond_wait函数是解锁等待(即:函数被调用后,互斥锁是出于解锁状态的。)这也是为什么demon1中,两个线程都加锁了,但是进入睡眠的打印信息都打印出来了,因为线程1调用该函数后,将锁解开了。
- pthread_cond_wait函数是解锁等待,也就是说,在该函数调用前必须要加锁,否则就谈不上解锁。那么pthread_cond_signal函数的调用过程中是否必须加锁呢???
- 以下示例的用法,未加任何判断条件的wait,阻塞,可以用作是线程间的通信,有点象Qt中的信号与槽的操作。
- pthread_cond_signal函数每次唤醒的线程未知,故此函数使用时,是针对一个生产者对应一个消费者的问题。
demon1——pthread_cond_signal
#include <stdio.h>
#include <pthread.h>
static pthread_t thread1;
static pthread_t thread2;
//静态初始化
static pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
void *function1()
{
while(1)
{
pthread_mutex_lock(&lock);
printf("===== 线程1进入睡眠 ====\n");
pthread_cond_wait(&cond,&lock);
printf("==== 线程1 唤醒 ====\n");
pthread_mutex_unlock(&lock);
}
}
void *function2()
{
while(1)
{
pthread_mutex_lock(&lock);
printf("===== 线程2进入睡眠 ====\n");
pthread_cond_wait(&cond,&lock);
printf("==== 线程2 唤醒 ====\n");
pthread_mutex_unlock(&lock);
}
}
int main()
{
int i=0;
if(-1==pthread_create(&thread1,NULL,function1,NULL))
{
printf("thread_create1 fail!\n");
pthread_detach(thread1);
}
if(-1==pthread_create(&thread2,NULL,function2,NULL))
{
printf("thread_create fail!\n");
pthread_detach(thread1);
}
while(1)
{
sleep(2);
i++;
printf("\n 第%d次唤醒\n",i);
pthread_mutex_lock(&lock);
if(-1==pthread_cond_signal(&cond))
{
printf("pthread_cond_broadcast error!\n");
}
pthread_mutex_unlock(&lock);
}
return 0;
}
运行结果:
demon2——pthread_cond_broadcast
#include <stdio.h>
#include <pthread.h>
static pthread_t thread1;
static pthread_t thread2;
//静态初始化
static pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
void *function1()
{
while(1)
{
pthread_mutex_lock(&lock);
printf("===== 线程1进入睡眠 ====\n");
pthread_cond_wait(&cond,&lock);
printf("==== 线程1 唤醒 ====\n");
pthread_mutex_unlock(&lock);
}
}
void *function2()
{
while(1)
{
pthread_mutex_lock(&lock);
printf("===== 线程2进入睡眠 ====\n");
pthread_cond_wait(&cond,&lock);
printf("==== 线程2 唤醒 ====\n");
pthread_mutex_unlock(&lock);
}
}
int main()
{
int i=0;
if(-1==pthread_create(&thread1,NULL,function1,NULL))
{
printf("thread_create1 fail!\n");
pthread_detach(thread1);
}
if(-1==pthread_create(&thread2,NULL,function2,NULL))
{
printf("thread_create fail!\n");
pthread_detach(thread1);
}
while(1)
{
sleep(2);
i++;
printf("\n 第%d次唤醒\n",i);
pthread_mutex_lock(&lock);
if(-1==pthread_cond_broadcast(&cond))
{
printf("pthread_cond_broadcast error!\n");
}
pthread_mutex_unlock(&lock);
}
return 0;
}
运行结果:
对比运行结果,清楚的可以发现pthread_cond_broadcast可以唤醒所有睡眠的线程