线程同步(2)条件变量

互斥锁有一个明显的缺点就是只有两种状态:锁定和非锁定,而条件变量通过允许线程阻塞和等待另个线程发送信号的方法来弥补互斥锁的不足。条件变量通常和互斥锁一起使用。

条件变量的结构为pthread_cond_t

涉及函数:

pthread_cond_init

pthread_cond_detroy

pthread_cond_wait

pthread_cond_timewait

pthread_cond_broadcast

pthread_cond_signal

简单测试用例为:

      1 #include <stdio.h>
      2 #include <stdlib.h>
      3 #include <pthread.h>
      4 typedef   enum{   true=1,false=0   }   bool;
      5 char buffer[128];
      6 bool buffer_has_data = false;
      7 pthread_mutex_t mutex;
      8 pthread_cond_t cond;
      9
     10 void write_buffer(char *data)
     11 {
     12     pthread_mutex_lock(&mutex);
     13     if (!buffer_has_data)
     14     {
     15         sprintf(buffer, "%s", data);
     16         buffer_has_data = true;
     17         pthread_cond_signal(&cond);
     18     }
     19     pthread_mutex_unlock(&mutex);
     20 }
     21 void read_buffer(void)
     22 {
     23     while (1)
     24     {
     25         pthread_mutex_lock(&mutex);
     26         while (!buffer_has_data)
     27         {
     28             pthread_cond_wait(&cond, &mutex);
     29         }
     30         if (buffer_has_data)
     31         {
     32             printf("Read buffer, data = [%s]\n", buffer);
     33             buffer_has_data = false;
     34         }
     35         pthread_mutex_unlock(&mutex);
     36         sleep(1);
     37     }
     38 }
     39
     40 int main( int argc, char **argv)
     41 {
     42     char input[128];
     43     pthread_t reader;
     44
     45     pthread_mutex_init(&mutex, NULL);
     46     pthread_cond_init(&cond, NULL);
     47     pthread_create(&reader, NULL, (void *)(read_buffer), NULL);
     48    
     49     while (1)
     50     {
     51         scanf("%s", input);
     52         write_buffer(input);
     53     }
     54     return 0;
     55 }

其实就是在互斥锁的基础上增加了条件变量的应用。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值