LinuxC多线程编程第五篇:线程通信(Condition)

来源:互联网 发布:端口号 传输层 编辑:程序博客网 时间:2024/06/07 02:55

分类: c/c++ 868人阅读 评论(2)收藏 举报
多线程编程signalstructnulljoin

        线程同步还有一种情况,线程1需要等某个条件成立才能继续往下执行,如果这个条件不成立,线程1就阻塞等待,线程2在执行某个条件成立了就唤醒线程1。这个和Java中的wait()和notify()其实是一样的

注意:最下面有本文演示的源码的链接地址

初始化与销毁通信条件

#include <pthread.h>
int pthread_cond_destroy(pthread_cond_t *cond);
int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr);
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
以上和上一篇中Mutex锁比较类似,我就不再重复。

具体实现函数

#include <pthread.h>
int pthread_cond_timedwait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex, const struct timespec *restrict abstime);
int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex);
int pthread_cond_broadcast(pthread_cond_t *cond);
int pthread_cond_signal(pthread_cond_t *cond);
这几个函数更加函数名就可以理解它的意思了,我就不多说。pthread_cond_signal、pthread_cond_broadcast与Java中notify、notifyAll()也是一样的。

pthread_cond_wait在一个conditon上阻塞等待,这个函数要做3个步骤:

  • 释放Mutex
  • 阻塞等待
  • 当其它线程调用pthread_cond_signal或pthread_cond_signal,它会重写获取锁。

我简单的写了一个阻塞栈,方便大家理解:

[cpp] view plaincopy
  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #include <pthread.h>  
  4. struct node{  
  5.      struct node* next;  
  6.      int number;  
  7. };   
  8.   
  9. pthread_cond_t hasNode = PTHREAD_COND_INITIALIZER;  
  10. pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;  
  11. struct node* head = NULL;  
  12. void* get(void *arg)  
  13. {  
  14.  struct node *node;  
  15.  while(1)   
  16.  {        
  17.    pthread_mutex_lock(&lock);   
  18.    if(head == NULL)  
  19.   {          
  20.     printf("has no data...\n");  
  21.      pthread_cond_wait(&hasNode,&lock);  
  22.    }  
  23.    node = head;  
  24.    head = node->next;  
  25.    printf("get the head node number:%d\n",node->number);  
  26.    pthread_mutex_unlock(&lock);  
  27.    free(node); //移除获取到的节点  
  28.    sleep(rand()%5);  
  29.    }  
  30. }  
  31.   
  32.   
  33. void* put(void *p)   
  34. {  
  35.  struct node* node;   
  36.   while(1)  
  37.  {       
  38.   node = malloc(sizeof(struct node));  
  39.   node->number = rand()%1000 +1;  
  40.   printf("put the head node number:%d\n",node->number);      
  41.   pthread_mutex_lock(&lock);  
  42.   node->next = head;  
  43.   head = node;  
  44.   pthread_mutex_unlock(&lock);  
  45.   pthread_cond_signal(&hasNode);  
  46.   sleep(rand()%5);        
  47. }  
  48.   
  49. }  
  50.   
  51.   
  52. int main(){  
  53. pthread_t pid,cid;  
  54. srand(time(NULL));  
  55. pthread_create(&pid,NULL,get,NULL);  
  56. pthread_create(&cid,NULL,put,NULL);  
  57. pthread_join(pid,NULL);  
  58. pthread_join(cid,NULL);  
  59. return 0;  
  60. }  

 

编译运行结果如下


 

 

源码下载:http://download.csdn.net/detail/jefry_xdz/4246164

0 0
原创粉丝点击