Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2112537
  • 博文数量: 438
  • 博客积分: 3871
  • 博客等级: 中校
  • 技术积分: 6075
  • 用 户 组: 普通用户
  • 注册时间: 2011-09-10 00:11
个人简介

邮箱: wangcong02345@163.com

文章分类

全部博文(438)

文章存档

2017年(15)

2016年(119)

2015年(91)

2014年(62)

2013年(56)

2012年(79)

2011年(16)

分类: LINUX

2015-08-03 17:44:08

1.
read_thread从终端输入一个个的字符,当遇到q字符时,发送cond_signal
write_thread一直在等侍signal,当收到read_thread发来的signal之后打印退出
2. 源码
  1. cong@msi:/work/test/thread/4cond$ cat cond.c
  2. #include "utils.h"
  3. pthread_mutex_t thread_mutex = PTHREAD_MUTEX_INITIALIZER;
  4. pthread_cond_t thread_cond = PTHREAD_COND_INITIALIZER;
  5. int c;
  6. void* read_thread(void* arg)
  7. {
  8.     while((c=getchar()) != 'q');
  9.     printf("read=%c\n", c);
  10.     printf("send signal\n");
  11.     pthread_cond_signal(&thread_cond);
  12.     return NULL;
  13. }

  14. void* write_thread(void* arg)
  15. {
  16.     pthread_mutex_lock(&thread_mutex);
  17.     printf("wait cond\n");
  18.     pthread_cond_wait(&thread_cond, &thread_mutex);
  19.     printf("write=%c\n", c);
  20.     pthread_mutex_unlock(&thread_mutex);
  21. }

  22. int main ( int argc, char *argv[] )
  23. {
  24.     pthread_t thread_id1;
  25.     pthread_t thread_id2;
  26.     void* thread_result;
  27.     int status;

  28.     status = pthread_create(&thread_id1, NULL, read_thread, NULL);
  29.     status = pthread_create(&thread_id2, NULL, write_thread, NULL);
  30.     
  31.     status = pthread_join(thread_id1, &thread_result);
  32.     status = pthread_join(thread_id2, &thread_result);

  33.     return EXIT_SUCCESS;
  34. }
运行结果
  1. cong@msi:/work/test/thread/4cond$ ./cond
  2. wait cond
  3. a
  4. b
  5. c
  6. d
  7. e
  8. f
  9. q
  10. read=q
  11. send signal
  12. write=q
4cond.rar (下载后改名为4cond.tar.gz)





阅读(1128) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~