- 论坛徽章:
- 0
|
本帖最后由 digdeep126 于 2011-11-23 12:39 编辑
兄弟,在main函数中的:pthread_create(&tid, NULL, thread_func, NULL);
后面加上sleep(2);就可以了:- int main(void)
- {
- pthread_t tid;
- struct node *p;
- int i;
- pthread_create(&tid, NULL, thread_func, NULL);
- sleep(2);
- for(i=0; i<10; i++){
- p = malloc(sizeof(struct node));
- p->n_number = i;
- p->n_next = NULL;
- pthread_mutex_lock(&mtx);
- p->n_next = head;
- head = p;
- pthread_cond_broadcast(&cond);
- pthread_mutex_unlock(&mtx);
- sleep(1);
- }
- printf("thread 1 wanna end the cancel thread 2.\n");
- pthread_cancel(tid);
- pthread_join(tid, NULL);
- printf("all done\n");
- return 0;
- }
-
复制代码 运行结果:
digdeep@ubuntu:~/pthread$ ./deadlock2
Got 0 from queue
Got 1 from queue
Got 2 from queue
Got 3 from queue
Got 4 from queue
Got 5 from queue
Got 6 from queue
Got 7 from queue
Got 8 from queue
Got 9 from queue
thread 1 wanna end the cancel thread 2.
cleanup handler pf second thread
all done
因为,static void *thread_func(void *arg)函数中的while(head == NULL)永远为假,无法进入这个while里面。
另外,你链表的操作很不规范。
另外,这是一个典型的“生产者-消费者”模型。 |
|