使用条件变量实现生产者消费者模型

1 #include<stdio.h>                                              
  2 #include<sys/wait.h>
  3 #include<unistd.h>
  4 #include<stdlib.h>
  5 #include<sys/types.h>
  6 #include<sys/stat.h>
  7 #include<string.h>
  8 #include<sys/socket.h>
  9 //#include<iostream>
 10 #include<fcntl.h>
 11 #include<sys/mman.h>
 12 #include<pthread.h>
 13 #include<signal.h>
 14 
 15 //using namespace std;
 16 
 17 //创建一个节点的结构
 18 typedef struct node
 19 {
 20     int data;
 21     struct node*next;
 22 }Node;
 23 
 24 //先定义出来一个头指针
 25 Node* head = NULL;
 26 
 27 //线程同步需要条件锁,互斥锁
 28 pthread_mutex_t mutex;
 29 pthread_cond_t cond;
 30 
 31 
 32 void * producer(void * arg){
 33     while(1){
 34         Node* p = (Node*)malloc(sizeof(Node));
 35         //节点的初始化
 36         p->data = rand()%1000;//0~99
 37 
 38         //使用胡吃锁保护共享数据
 39         pthread_mutex_lock(&mutex);
              //指针域
 42         p->next = head;
 43         head = p;
 44         //cout<<"chuang jian :"<<pthread_self()<<p->data<<endl;
 45         printf("chuang jian :%lu, data :%d \n",pthread_self(),p    ->data);
 46 
 47         pthread_mutex_unlock(&mutex);
 48 
 49         //通知阻塞的消费者线程,解除阻塞
 50         pthread_cond_signal(&cond);
 51 
 52         sleep(rand()%3);
 53     }
 54     return NULL;
 55 }
 56 
 57 void customer(void * arg){
 58     while(1){
 59 
 60         pthread_mutex_lock(&mutex);
 61 
 62         //判断链表是否为空
 63         if(head == NULL){
 64             //线程阻塞色-对胡吃锁解锁
 65             pthread_cond_wait(&cond,&mutex);
 66             //解除则色之后,会对胡吃锁在做枷锁
 67         }
 68 
 69         //链表不为空,删除一个节点
 70         Node* pdel = head;
 71         head = head->next;
 72         //cout<<"shan chu :"<<pthread_self()<<pdel->data<<endl;
 73         printf("xiao fei :%lu, data :%d \n",pthread_self(),pdel    ->data);
 74         free(pdel);
 75         pthread_mutex_unlock(&mutex);
 76     }
 77     return NULL;                      
        }
         int main(int argc,const char* argv[]){
 81 
 82     //创建生产者线程:
 83     pthread_mutex_init(&mutex,NULL);
 84     pthread_cond_init(&cond,NULL);
 85 
 86 
 87     pthread_t p1;
 88     pthread_t p2;
 89 
 90     pthread_create(&p1,NULL,producer,NULL);
 91     //创建消费者线程
 92     pthread_create(&p2,NULL,customer,NULL);
 93 
 94     //阻塞回收
 95     pthread_join(&p1,NULL);
 96     pthread_join(&p2,NULL);
 97     
 98     pthread_mutex_destroy(&mutex);
 99     pthread_cond_destroy(&cond);
100 
101     return 0;
102 }                            
	

  

猜你喜欢

转载自www.cnblogs.com/yjds/p/9061671.html
今日推荐