线程间通讯《代码》pthread_cond_t

  1. #define _GNU_SOURCE
  2. #include <unistd.h>
  3. #include <pthread.h>
  4.  
  5. #include <stdlib.h>
  6. #include <stdio.h>
  7.  
  8. //static pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;
  9. // 这里虽然是 P/V ,但是用 cond 确实更方便。
  10. static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
  11. static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  12.  
  13. int i = 0;
  14.  
  15. void get ( )
  16. {
  17. pthread_mutex_lock (&mutex );
  18. while ( i == 0 ) // 队列下限
  19. pthread_cond_wait (&cond, &mutex ); // 唤醒其它线程进行检测。
  20.  
  21. --i;
  22. pthread_cond_signal (&cond );
  23. printf ( "Current size: %d\n", i );
  24.  
  25. pthread_mutex_unlock (&mutex );
  26. }
  27.  
  28. void put ( )
  29. {
  30. pthread_mutex_lock (&mutex );
  31. while ( i == 3 ) // 队列上限
  32. pthread_cond_wait (&cond, &mutex );
  33.  
  34. ++i;
  35. pthread_cond_signal (&cond ); // 唤醒其它线程
  36. printf ( "Now size: %d\n", i );
  37.  
  38. pthread_mutex_unlock (&mutex );
  39. }
  40.  
  41. void *thf ( void *arg )
  42. {
  43. while ( 1 )
  44. {
  45. put ( );
  46. }
  47. }
  48.  
  49. int main ( )
  50. {
  51. pthread_t tid;
  52. pthread_create (&tid, NULL, thf, NULL );
  53.  
  54. sleep ( 3 );
  55. while ( 1 )
  56. get ( );
  57. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值