声明
以下内容仅供学习,如有侵权,联系作者删除。
参考文献:B站up主:C语言技术网
链接: C语言技术网–Linux多线程
条件变量
int pthread_cond_destroy(pthread_cond_t *cond);
int pthread_cond_init(pthread_cond_t *restrict cond,
const pthread_condattr_t *restrict attr);
int pthread_cond_broadcast(pthread_cond_t *cond);
int pthread_cond_signal(pthread_cond_t *cond);
int pthread_cond_wait(pthread_cond_t *restrict cond,
pthread_mutex_t *restrict mutex);
示例
/*
* 程序启动后,等待条件满足,唤醒线程,执行线程函数。
* 作者:jack 日期:20210619
* 参考作者:C语言技术网(www.freecplus.net), B站UP主:C语言技术网
*/
#include <stdio.h>
#include <pthread.h>
#include<unistd.h>
#include <signal.h>
pthread_mutex_t mutex; // 声明互斥锁
pthread_cond_t cond; // 声明条件变量
void *thread1(void *arg)
{
while(1)
{
pthread_cond_wait(&cond, &mutex);
printf("线程一被唤醒。\n");
}
}
void *thread2(void *arg)
{
while(1)
{
pthread_cond_wait(&cond, &mutex);
printf("线程二被唤醒。\n");
}
}
void func(int sig)
{
pthread_cond_signal(&cond);
//pthread_cond_broadcast(&cond);
}
int main()
{
signal(15, func);
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond,NULL);
pthread_t pthid1, pthid2;
pthread_create(&pthid1, NULL, thread1, (void *)1);
pthread_create(&pthid2, NULL, thread2, (void *)2);
pthread_join(pthid1, NULL);
pthread_join(pthid2, NULL);
return 0;
}
执行结果
启动程序后:
再开第二个窗口:
则第一个窗口执行结果如下:
再到第二个窗口执行发信号操作:则第一个窗口执行结果如下:
小结
接下来结合互斥锁和条件变量来讲。