线程中的条件锁

线程中的条件锁

线程的主要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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值