线程中的条件锁
线程的主要API
1、创建及销毁条件变量
#include <pthread.h>
int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr);
int pthread_cond_destroy(pthread_cond_t *cond);
// 返回:若成功返回0,否则返回错误编号
除非需要创建一个非默认属性的条件变量,否则pthread_cont_init函数的attr参数可以设置为NULL。
2、等待
#include <pthread.h>
int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex);
int pthread_cond_timedwait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex, cond struct timespec *restrict timeout);
// 返回:若成功返回0,否则返回错误编号
3、触发
#include <pthread.h>
int pthread_cond_signal(pthread_cond_t cond);
int pthread_cond_broadcast(pthread_cond_t cond);
// 返回:若成功返回0,否则返回错误编号
这两个函数可以用于通知线程条件已经满足。pthread_cond_signal函数将唤醒等待该条件的某个线程,而pthread_cond_broadcast函数将唤醒等待该条件的所有进程。
下面是试例代码
#include<stdio.h>
#include<pthread.h>
int data=0;
pthread_mutex_t mutex;
pthread_cond_t cond;//全局定义
void *fun1(void *arg)
{
while(1)
{
pthread_cond_wait(&cond,&mutex);//条件等待
printf("t1 data=%d\n",data);
printf("t1 run=======================\n");
data=0;
sleep(1);
}
}
void *fun2(void *arg)
{
while(1)
{
printf("t2 data=%d\n",data);
pthread_mutex_lock(&mutex);
data++;
if(data==3)
{
pthread_cond_signal(&cond);//条件发送
}
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
int main()
{
pthread_t t1;
pthread_t t2;
int ret;
pthread_mutex_init(&mutex,NULL);
pthread_cond_init(&cond,NULL);//初始化条件
ret=pthread_create(&t1,NULL,fun1,NULL);
ret=pthread_create(&t2,NULL,fun2,NULL);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);//退出条件
return 0;
}
主要思想是 让全局变量data加到3的时候触发线程1