线程通信之条件变量pthread_cond_t

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

pthread_cond_t cond_p;
pthread_cond_t cond_c;
pthread_mutex_t mutex;
int share_cond;

void* productor(void * argc)
{
   while(1)
   {
   pthread_mutex_lock(&mutex);
   if(share_cond>=10)
   {

        printf("produc is very enougsh\n");
        pthread_cond_signal(&cond_c);
        pthread_cond_wait(&cond_p,&mutex);
   }
   share_cond++;

   printf("product has  %d\n",share_cond);
   pthread_mutex_unlock(&mutex);
   sleep(2);
   }
   return NULL;
}

void* consumer(void *argc)
{
  while(1)
   {
    pthread_mutex_lock(&mutex);
    if(share_cond<=0)
    {
        printf("produc is not enougsh\n");
        pthread_cond_signal(&cond_p);
        pthread_cond_wait(&cond_c,&mutex);
   }
   share_cond--;
printf("proctor remains %d\n",share_cond);
   pthread_mutex_unlock(&mutex);
   sleep(1);
   }

   return NULL;
}
int main()
{
  pthread_cond_init(&cond_p,NULL);
  pthread_cond_init(&cond_c,NULL);
  pthread_mutex_init(&mutex,NULL);
  pthread_t tid_productor,tid_consumer;
  pthread_create(&tid_productor,NULL,productor,NULL);
  pthread_create(&tid_consumer,NULL,consumer,NULL);

  pthread_join(tid_productor,NULL);
  pthread_join(tid_productor,NULL);

  pthread_cond_destroy(&cond_c);
  pthread_cond_destroy(&cond_p);
  pthread_mutex_destroy(&mutex);

  printf("pthread_cond_t test\n");
  return 0;
}

                           

线程间通过发pthread_cond_t和全局变量来实现线程间的同步,本demo实现了一个生产者与消费者模式。

使用pthread_cond_t需要注意的有以下3点

1.必须配合互斥量pthread_mutex_t来使用

2.pthread_cond_sign须在mutex unlock之前调用

3.pthread_cond_wait()函数一进入wait状态就会自动release mutex

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值