条件变量的用法示例

条件变量示例

条件变量最常用的场景是生产者和消费者模型

常见问题1:为什么条件变量要传入互斥锁

因为pthread_cond_wait里的操作会产生冲突(具体也不明白),调用前需要加锁,调用的过程中锁会释放,调用结束或又会上锁。总之锁传进去是会被操作的,先释放,被pthread_cond_signal激活后,又会上锁。

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

pthread_mutex_t mutex;
pthread_cond_t cond;

struct Node{
    int value;
    Node *next;
    Node(int val) {
        value = val;
        next  = NULL;
    }
};

Node *head;

static  void * producer(void *) {
    static int cnt = 0;
    while(1) {
        Node *tmp = new Node(cnt++);
        printf("producer lock\n");
        pthread_mutex_lock(&mutex);
        printf("producer produce food :%d\n", tmp->value);
        tmp->next = head;
        head      = tmp;
        printf("producer unlock\n");
        pthread_mutex_unlock(&mutex);
        printf("buy buy buy!!!\n");
        pthread_cond_signal(&cond);
        sleep(1);
    }
}

static void * comsumer(void *) {
    while(1) {
        printf("comsumer lock\n");
        pthread_mutex_lock(&mutex);
        while(head == NULL) {
            printf("comsumer wait...\n");
            pthread_cond_wait(&cond, &mutex);
        }
        printf("comsumer start eating\n");
        Node *tmp = head;
        printf("comsumer eating %d\n", head->value);
        head      = head->next;
        printf("comsumer unlock\n");
        pthread_mutex_unlock(&mutex);
        delete tmp;
    }
    return NULL;
}

int main(int argc, char ** argv) {
    pthread_t producedThread, comsumerThread;
    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&cond, NULL);
    pthread_create(&producedThread, NULL, producer, NULL);
    pthread_create(&comsumerThread, NULL, comsumer, NULL);
    pthread_join(producedThread, NULL);
    pthread_join(comsumerThread, NULL);
    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值