pthread9.2

/* pthread9-2.c 条件变量(生产者与消费者的关系)*/

#include <pthread.h>

#include <stdio.h>

pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;

pthread_cond_t cond=PTHREAD_COND_INITIALIZER;

int count=5;

void *decrement(void *arg)//消费

{

  while(1)

  {

     pthread_mutex_lock(&mutex);

     //printf("thread1 got lock!\n");

     while(count<=0)

    {

      printf("count<=0,thread1 is hanging!\n");//线程1正在挂起!

      pthread_cond_wait(&cond,&mutex);

      sleep(1);

      printf("sleep!\n");

    }

   count=count-1;

   pthread_mutex_unlock(&mutex);  

   //printf("thread1 released the lock!\n");

   if(count==9)

    {

      printf("count=9,thread1 is over!\n");

      return NULL;

    }

  }

}

void *increment(void *arg)//生产

{

  sleep(1);

  while(1)

  {

     pthread_mutex_lock(&mutex);

     //printf("thread2 got lock!\n");

     count=count+1;

     if(count>0)

    {

      printf("count=%d,change cond state!\n",count);

      pthread_cond_signal(&cond);

    }

   pthread_mutex_unlock(&mutex);

   //printf("thread2 released the lock!\n");


 

   if(count==10)

    {

      printf("count=10,thread2 is over!\n");

      return NULL;

    }

 }

}

int main()

{

    int i1=1,i2=1;

    pthread_t id1,id2;

   pthread_mutex_init(&mutex,NULL);

   pthread_cond_init(&cond,NULL);

   pthread_create(&id1,NULL,decrement,NULL);//消费

   pthread_create(&id2,NULL,increment,NULL);//生产

   

   i2=pthread_join(id2,NULL);

   i1=pthread_join(id1,NULL);

   if((i2==0)&&(i1==0))

    {

      printf("count=%d,the main thread!\n",count);

      pthread_cond_destroy(&cond);

      pthread_mutex_destroy(&mutex);

      return 0;

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值