多线程条件变量

#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <pthread.h>

struct stu_t{
    int dowait;
    pthread_cond_t cond;
    pthread_mutex_t mutex;
};
struct stu_t stu;


void* do_send(void* args){
    pthread_mutex_lock(&(stu.mutex));
    printf("do send get the locki\n");
    if(stu.dowait==0){
        printf("do send before send signal\n");
        stu.dowait=1;
        pthread_cond_signal(&(stu.cond));
        printf("do send after send signal\n");
    }

    pthread_mutex_unlock(&(stu.mutex));
    printf("end of send signal\n");
}
void* do_wait(void *args){
    pthread_mutex_lock(&(stu.mutex));
        printf("do wait get the lock\n");
    while(stu.dowait==0)
    {
        printf("dowait before cond wait\n");

        pthread_cond_wait(&(stu.cond),&(stu.mutex));
        
        printf("dowait after cond wait\n");

    }

    printf("*************************");
    stu.dowait==0;
    // do other other things 
    
    printf("#####################");
    pthread_mutex_unlock(&(stu.mutex));
}

int main(){
    pthread_t tid1,tid2;
    stu.dowait=0;
    pthread_mutex_init(&(stu.mutex),NULL);
    pthread_cond_init(&(stu.cond),NULL);
    pthread_create(&tid1,NULL,do_wait,NULL);
    pthread_create(&tid2,NULL,do_send,NULL);
    sleep(3);
}

示例代码。

PS在do_send中unlock和signal调用顺序任意都可以。

转载于:https://www.cnblogs.com/shenshenlei/p/5983900.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值