Chinaunix首页 | 论坛 | 博客
  • 博客访问: 746676
  • 博文数量: 96
  • 博客积分: 2023
  • 博客等级: 上尉
  • 技术积分: 1738
  • 用 户 组: 普通用户
  • 注册时间: 2012-03-15 10:03
文章分类

全部博文(96)

文章存档

2014年(11)

2012年(85)

分类: LINUX

2012-04-24 11:02:22

说明,
等待线程
1。使用pthread_cond_wait前要先加锁
2。pthread_cond_wait内部会解锁,然后等待条件变量被其它线程激活
3。pthread_cond_wait被激活后会再自动加锁

激活线程:
1。加锁(和等待线程用同一个锁)
2。pthread_cond_signal发送信号
3。解锁
激活线程的上面三个操作在运行时间上都在等待线程的pthread_cond_wait函数内部。

程序示例:


点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <unistd.h>

  4. pthread_mutex_t count_lock;
  5. pthread_cond_t count_nonzero;
  6. unsigned count = 0;

  7. void * decrement_count(void *arg) {
  8. pthread_mutex_lock (&count_lock);
  9. printf("decrement_count get count_lock\n");
  10. while(count==0) {
  11. printf("decrement_count count == 0 \n");
  12. printf("decrement_count before cond_wait \n");
  13. pthread_cond_wait( &count_nonzero, &count_lock);
  14. printf("decrement_count after cond_wait \n");
  15. }
  16. count = count -1;
  17. pthread_mutex_unlock (&count_lock);
  18. }

  19. void * increment_count(void *arg){
  20. pthread_mutex_lock(&count_lock);
  21. printf("increment_count get count_lock\n");
  22. if(count==0) {
  23. printf("increment_count before cond_signal\n");
  24. pthread_cond_signal(&count_nonzero);
  25. printf("increment_count after cond_signal\n");
  26. }
  27. count=count+1;
  28. pthread_mutex_unlock(&count_lock);
  29. }

  30. int main(void)
  31. {
  32. pthread_t tid1,tid2;

  33. pthread_mutex_init(&count_lock,NULL);
  34. pthread_cond_init(&count_nonzero,NULL);

  35. pthread_create(&tid1,NULL,decrement_count,NULL);
  36. sleep(2);
  37. pthread_create(&tid2,NULL,increment_count,NULL);

  38. sleep(10);
  39. pthread_exit(0);
  40. }
阅读(1013) | 评论(0) | 转发(0) |
0

上一篇:sed入门学习

下一篇:String.Format

给主人留下些什么吧!~~