linux编程之条件变量

7 篇文章 0 订阅

Linux下条件变量pthread_cond_t在使用的时候必须要配合一把互斥锁pthread_mutex_t来使用,为什么会这样呢?其实我们自己想办法做一个条件变量,要达到条件变量的效果,也是必须加互斥锁才能完成的。

假如,有这样一个场景,一个读线程、一个写线程,一个设置标记线程。当设置标记线程将标记更改为true时,我们允许读、写线程工作,否则让读、写线程等待。

首先我们不适用系统提供的条件变量,自己想办法实现一个类似条件变量功能的方法,

首先我们需要设立一个全局变量,flag,当该变量值为true时,读写线程开始工作,当该值为false时,读写线程等待。为了保证对flag变量操作的原子性,我们必须准备一个互斥锁mutex用来保护flag变量。

在上面这个例子中flag就类似与pthread_cond_t,我们准备的mutex类似与pthread_mutex_t,要实现条件变量作用,这两个变量必须配合工作,才能达到效果。

下面我们给一段,Linux下使用条件变量的案例程序:

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

pthread_mutex_t period_lock;
pthread_cond_t period_cond;

void *read_thread(void *arg)
{
    while(1)
    {
        pthread_mutex_lock(&period_lock);
        printf("read thread lock period_lock.\n");
        pthread_cond_wait(&period_cond, &period_lock);
        printf("read thread start work. \n");
        printf("read thread end work. \n");

        pthread_mutex_unlock(&period_lock);
        printf("read thread unlock period_lock.\n");
    }
}

void *write_thread(void *arg)
{
    while(1)
    {
        pthread_mutex_lock(&period_lock);
        printf("write thread lock period_lock.\n");
        pthread_cond_wait(&period_cond, &period_lock);
        printf("write thread start work. \n");
        printf("write thread end work. \n");
        pthread_mutex_unlock(&period_lock);
        printf("write thread unlock period_lock.\n");
    }
}

void *modify_period_thread(void *arg)
{
    while(1)
    {
        printf("\n\n\n \n");
        pthread_mutex_lock(&period_lock);
        printf("modify period thread lock period_lock. \n");
        printf("modify thread start work. \n");
        printf("modify thread end work. \n");
        pthread_cond_broadcast(&period_cond);
        printf("modify thread send signal. \n");
        pthread_mutex_unlock(&period_lock);
        printf("modify period thread unlock period_lock. \n");
        
        usleep(3 * 1000 * 1000);
    }
}

int main(void)
{
    pthread_t tid_read, tid_write, tid_modify_period;

    pthread_mutex_init(&period_lock, NULL);
    pthread_cond_init(&period_cond, NULL);

    printf("start create thread. \n");
    pthread_create(&tid_read, NULL, read_thread, NULL);
    pthread_create(&tid_write, NULL, write_thread, NULL);
    pthread_create(&tid_modify_period, NULL, modify_period_thread, NULL);
    printf("end create thread. \n");

    sleep(10);
    pthread_exit(0);

    return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

heibao111728

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值