设为首页 加入收藏

TOP

pthread_cond_wait()用法分析(二)
2011-12-30 12:56:57 】 浏览:2576
Tags:pthread_cond_wait 用法 分析
 

 

现在来看一段典型的应用:看注释即可。

  1. #include <pthread.h>  
  2. #include <unistd.h>  
  3.   
  4. static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;  
  5. static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;  
  6.   
  7. struct node {  
  8. int n_number;  
  9. struct node *n_next;  
  10. } *head = NULL;  
  11.   
  12. /*[thread_func]*/  
  13. static void cleanup_handler(void *arg)  
  14. {  
  15.     printf("Cleanup handler of second thread./n");  
  16.     free(arg);  
  17.     (void)pthread_mutex_unlock(&mtx);  
  18. }  
  19. static void *thread_func(void *arg)  
  20. {  
  21.     struct node *p = NULL;  
  22.   
  23.     pthread_cleanup_push(cleanup_handler, p);  
  24.     while (1) {  
  25.     pthread_mutex_lock(&mtx);           //这个mutex主要是用来保证pthread_cond_wait的并发性  
  26.     while (head == NULL)   {               //这个while要特别说明一下,单个pthread_cond_wait功能很完善,为何这里要有一个while (head == NULL)呢?因为pthread_cond_wait里的线程可能会被意外唤醒,如果这个时候head != NULL,则不是我们想要的情况。这个时候,应该让线程继续进入pthread_cond_wait  
  27.         pthread_cond_wait(&cond, &mtx);         // pthread_cond_wait会先解除之前的pthread_mutex_lock锁定的mtx,然后阻塞在等待对列里休眠,直到再次被唤醒(大多数情况下是等待的条件成立而被唤醒,唤醒后,该进程会先锁定先pthread_mutex_lock(&mtx);,再读取资源  
  28.                                                 //用这个流程是比较清楚的/*block-->unlock-->wait() return-->lock*/  
  29.     }  
  30.         p = head;  
  31.         head = head->n_next;  
  32.         printf("Got %d from front of queue/n", p->n_number);  
  33.         free(p);  
  34.         pthread_mutex_unlock(&mtx);             //临界区数据操作完毕,释放互斥锁  
  35.     }  
  36.     pthread_cleanup_pop(0);  
  37.     return 0;  
  38. }  
  39.   
  40. int main(void)  
  41. {  
  42.     pthread_t tid;  
  43.     int i;  
  44.     struct node *p;  
  45.     pthread_create(&tid, NULL, thread_func, NULL);   //子线程会一直等待资源,类似生产者和消费者,但是这里的消费者可以是多个消费者,而不仅仅支持普通的单个消费者,这个模型虽然简单,但是很强大  
  46.     /*[tx6-main]*/  
  47.     for (i = 0; i < 10; i++) {  
  48.         p = malloc(sizeof(struct node));  
  49.         p->n_number = i;  
  50.         pthread_mutex_lock(&mtx);             //需要操作head这个临界资源,先加锁,  
  51.         p->n_next = head;  
  52.         head = p;  
  53.         pthread_cond_signal(&cond);  
  54.         pthread_mutex_unlock(&mtx);           //解锁  
  55.         sleep(1);  
  56.     }  
  57.     printf("thread 1 wanna end the line.So cancel thread 2./n");  
  58.     pthread_cancel(tid);             //关于pthread_cancel,有一点额外的说明,它是从外部终止子线程,子线程会在最近的取消点,退出线程,而在我们的代码里,最近的取消点肯定就是pthread_cond_wait()了。关于取消点的信息,有兴趣可以google,这里不多说了  
  59.     pthread_join(tid, NULL);  
  60.     printf("All done -- exiting/n");  
  61.     return 0;  
  62. }  
首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇理解pthread_cond_wait() 下一篇C/C++正则表达式应用

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目