Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1755632
  • 博文数量: 413
  • 博客积分: 8399
  • 博客等级: 中将
  • 技术积分: 4325
  • 用 户 组: 普通用户
  • 注册时间: 2011-06-09 10:44
文章分类

全部博文(413)

文章存档

2015年(1)

2014年(18)

2013年(39)

2012年(163)

2011年(192)

分类: C/C++

2011-11-06 20:58:31

在用pthread函数库实现一个线程池的过程中,遇到了几个小小的问题:

(1)pthread_cond_signal对一个已经被cancel的线程发信号时,会导致死锁的发生。实验的代码如下:
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <pthread.h>

  4. int x = 10, y;
  5. pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
  6. pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

  7. void* fun1(void *arg)
  8. {
  9.         pthread_mutex_lock(&lock);
  10.         printf("x: %d\ty: %d\n", x, y);
  11.         while(x >= y){
  12.                 pthread_cond_wait(&cond, &lock);
  13.         }
  14.         printf("OH, My God, y is bigger than x.\n");
  15.         pthread_mutex_unlock(&lock);
  16.         return NULL;
  17. }
  18.                 
  19. void* fun2(void *arg)
  20. {
  21.         pthread_mutex_lock(&lock);
  22.         while(1){
  23.                 y++;
  24.                 printf("x: %d\ty: %d\n", x, y);
  25.                 sleep(1);
  26.                 if(y == 5){
  27.                         pthread_mutex_unlock(&lock);
  28.                         sleep(1);
  29.                         pthread_mutex_lock(&lock);
  30.                 }
  31.                 if(x < y){
  32.                         pthread_cond_signal(&cond);
  33.                         pthread_mutex_unlock(&lock);
  34.                         break;
  35.                 }
  36.         }
  37.         return NULL;
  38. }

  39. int main()
  40. {
  41.         pthread_t tid1, tid2;

  42.         pthread_create(&tid2, NULL, fun2, NULL);
  43.         sleep(1);
  44.         pthread_create(&tid1, NULL, fun1, NULL);
  45.         sleep(1);
  46.         pthread_cancel(tid1);
  47.         sleep(1);
  48.         pthread_join(tid1, NULL);
  49.         pthread_join(tid2, NULL);
  50.         return 0;
  51. }
当我们将main()函数中的:pthread_cancel(tid1)注释掉时,编译运行的结果为:
  1. digdeep@ubuntu:~/pthread/threadpool$ gcc -Wall -lpthread -o cond cond.c
  2. digdeep@ubuntu:~/pthread/threadpool$ ./cond
  3. x: 10    y: 1
  4. x: 10    y: 2
  5. x: 10    y: 3
  6. x: 10    y: 4
  7. x: 10    y: 5
  8. x: 10    y: 5
  9. x: 10    y: 6
  10. x: 10    y: 7
  11. x: 10    y: 8
  12. x: 10    y: 9
  13. x: 10    y: 10
  14. x: 10    y: 11
  15. OH, My God, y is bigger than x.
当我们没有将main()函数中的:pthread_cancel(tid1)注释掉时,编译运行的结果为:
  1. digdeep@ubuntu:~/pthread/threadpool$ gcc -Wall -lpthread -o cond cond.c
  2. digdeep@ubuntu:~/pthread/threadpool$ ./cond
  3. x: 10    y: 1
  4. x: 10    y: 2
  5. x: 10    y: 3
  6. x: 10    y: 4
  7. x: 10    y: 5

在输出:x: 10    y: 5 之后,发生了死锁。



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

digdeep1262011-11-07 18:39:14

kd98u9: 进来学习啦.....
一起学习。Fighting!

kd98u92011-11-07 18:10:33

进来学习啦