当前位置: 代码迷 >> 综合 >> pthread_cond_broadcast与pthread_cond_signal的区别——linuxc
  详细解决方案

pthread_cond_broadcast与pthread_cond_signal的区别——linuxc

热度:46   发布时间:2024-02-09 16:19:24.0

pthread_cond_signal——唤醒睡眠的线程,一次只能唤醒一个线程
pthread_cond_broadcast——唤醒睡眠的线程,一次唤醒所有睡眠的线程

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可以唤醒所有睡眠的线程