线程通信之条件变量pthread_cond_t

#include
#include
#include
#include
#include

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

 

 

你可能感兴趣的:(Linuxc)