Linux C 线程同步实例分析(二)

这是一个使用条件变量的例子,后面的附图很清楚的说明了整个过程中互斥量的加锁和解锁的过程。

/*
*条件变量使用例程
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

static pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond=PTHREAD_COND_INITIALIZER;

static int x=0;

/*消费者线程工作函数*/
static void* thread_eat(void* arg)
{
    int id=(int)arg;
    printf("thread %d run\n",id);
    while(1){
        pthread_mutex_lock(&lock);
        /*判断条件是否满足,如果 x<=0,则等待条件变量cond*/
        while(x<=0){
            printf("thread %d will wait on cond\n",id);
            pthread_cond_wait(&cond,&lock);
            printf("thread %d wakeup \n",id);
        }
        x--;
        printf("thread %d eat one,now x=%d\n",id,x);
        pthread_mutex_unlock(&lock);
        sleep(1);
    }
    return NULL;
}

/*生产者*/
static void* thread_feed(void* arg)
{
    while(1){
        pthread_mutex_lock(&lock);
        x+=4;
        /*触发条件变量*/
        pthread_cond_broadcast(&cond);
        printf("thread feed set x=%d\n",x);
        pthread_mutex_unlock(&lock);
        sleep(2);
    }
    return NULL;
}

int main()
{   
    int i;
    pthread_t tid;
    for(i=0;i<3;++i){
        if(pthread_create(&tid,NULL,thread_eat,(void*)i)){
            perror("pthread_create");
            return -1;
        }
    }
    sleep(6);  /*保证消费者先运行*/
    if(pthread_create(&tid,NULL,thread_feed,NULL)){
        perror("pthread_create");
        return -1;
    }
    pthread_join(tid,NULL);
   
    return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值