在用pthread函数库实现一个线程池的过程中,遇到了几个小小的问题:
(1)pthread_cond_signal对一个已经被cancel的线程发信号时,会导致死锁的发生。实验的代码如下:
- #include <stdio.h>
-
#include <unistd.h>
-
#include <pthread.h>
-
-
int x = 10, y;
-
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
-
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
-
-
void* fun1(void *arg)
-
{
-
pthread_mutex_lock(&lock);
-
printf("x: %d\ty: %d\n", x, y);
-
while(x >= y){
-
pthread_cond_wait(&cond, &lock);
-
}
-
printf("OH, My God, y is bigger than x.\n");
-
pthread_mutex_unlock(&lock);
-
return NULL;
-
}
-
-
void* fun2(void *arg)
-
{
-
pthread_mutex_lock(&lock);
-
while(1){
-
y++;
-
printf("x: %d\ty: %d\n", x, y);
-
sleep(1);
-
if(y == 5){
-
pthread_mutex_unlock(&lock);
-
sleep(1);
-
pthread_mutex_lock(&lock);
-
}
-
if(x < y){
-
pthread_cond_signal(&cond);
-
pthread_mutex_unlock(&lock);
-
break;
-
}
-
}
-
return NULL;
-
}
-
-
int main()
-
{
-
pthread_t tid1, tid2;
-
-
pthread_create(&tid2, NULL, fun2, NULL);
-
sleep(1);
-
pthread_create(&tid1, NULL, fun1, NULL);
-
sleep(1);
-
pthread_cancel(tid1);
-
sleep(1);
-
pthread_join(tid1, NULL);
-
pthread_join(tid2, NULL);
-
return 0;
-
}
当我们将main()函数中的:pthread_cancel(tid1); 注释掉时,编译运行的结果为:
- digdeep@ubuntu:~/pthread/threadpool$ gcc -Wall -lpthread -o cond cond.c
-
digdeep@ubuntu:~/pthread/threadpool$ ./cond
-
x: 10 y: 1
-
x: 10 y: 2
-
x: 10 y: 3
-
x: 10 y: 4
-
x: 10 y: 5
-
x: 10 y: 5
-
x: 10 y: 6
-
x: 10 y: 7
-
x: 10 y: 8
-
x: 10 y: 9
-
x: 10 y: 10
-
x: 10 y: 11
-
OH, My God, y is bigger than x.
当我们没有将main()函数中的:pthread_cancel(tid1); 注释掉时,编译运行的结果为:
- digdeep@ubuntu:~/pthread/threadpool$ gcc -Wall -lpthread -o cond cond.c
-
digdeep@ubuntu:~/pthread/threadpool$ ./cond
-
x: 10 y: 1
-
x: 10 y: 2
-
x: 10 y: 3
-
x: 10 y: 4
-
x: 10 y: 5
在输出:x: 10 y: 5 之后,发生了死锁。
阅读(3918) | 评论(2) | 转发(1) |