经典:生产者消费者模型

来源:互联网 发布:如何注册淘宝达人 编辑:程序博客网 时间:2024/06/07 04:52

首先是用信号量实现的

#include <stdio.h>#include <pthread.h>#include <time.h>#include <string.h>#include <semaphore.h>//信号量和缓冲区struct data{sem_t producer;  //用来控制生产者,只有缓冲区为空,生产者才可以生产消息sem_t customer;  //用来控制消费者,只有缓冲区有数据,才可以消费char buf[32];   //缓冲区};struct data model;void* producer_do(void *a){char *buf[] = {"香蕉","菠萝","橙子","西瓜","苹果","黄瓜","橘子"};while(1){int time = rand() % 100 + 1;usleep(time* 10000);sem_wait(&model.producer);   // pstrcpy(model.buf,buf[rand()%7]);printf("生产的一个水果:%s\n",model.buf);sem_post(&model.customer);   // v}}void* customer_do(void *a){while(1){int time = rand() % 100 + 1;usleep(time* 10000);sem_wait(&model.customer);   // pprintf("吃了一个水果:%s\n",model.buf);sem_post(&model.producer);   // v}}int main(){srand((unsigned int)time(NULL));//信号量初始化sem_init(&model.producer,0,1);sem_init(&model.customer,0,0);pthread_t producer_id;pthread_t customer_id;//生产者线程pthread_create(&producer_id,NULL,producer_do,NULL);//消费者线程pthread_create(&customer_id,NULL,customer_do,NULL);//等待线程pthread_join(producer_id,NULL);pthread_join(customer_id,NULL);//销毁信号量sem_destroy(&model.producer);sem_destroy(&model.customer);return 0;}

然后再加上互斥锁的

#include <stdio.h>#include <pthread.h>#include <time.h>//#include <string.h>#include <semaphore.h>#include "SqQuenue.h"//声明信号量struct data{sem_t producer;sem_t customer;QUEUE q;};//互斥锁pthread_mutex_t mutex;//创建信号量struct data model;//创建计数Queue_data num = 0;//生产者线程void* producer_do(void *a){while(1){int time = rand() % 100 + 1;usleep(time* 10000);sem_wait(&model.producer);   // ppthread_mutex_lock(&mutex);  //开锁num++;PushQueue(&(model.q),num);printf("生产了一个编号为%d的水果\n",num);pthread_mutex_unlock(&mutex);  //解锁sem_post(&model.customer);   // v}}//消费者线程void* customer_do(void *a){while(1){int time = rand() % 100 + 1;usleep(time* 10000);sem_wait(&model.customer);   // ppthread_mutex_lock(&mutex);  //开锁Queue_data x;PopQueue(&(model.q),&x);printf("消费了一个编号为%d的水果\n",x);pthread_mutex_unlock(&mutex);  //解锁sem_post(&model.producer);   // v}}int main(){srand((unsigned int)time(NULL));//信号量初始化sem_init(&model.producer,0,10);sem_init(&model.customer,0,0);//初始化互斥锁pthread_mutex_init(&mutex, NULL);//初始化队列Initqueue(&(model.q));pthread_t producer_id;pthread_t customer_id;//生产者线程pthread_create(&producer_id,NULL,producer_do,NULL);//消费者线程pthread_create(&customer_id,NULL,customer_do,NULL);//等待线程pthread_join(producer_id,NULL);pthread_join(customer_id,NULL);//销毁信号量sem_destroy(&model.producer);sem_destroy(&model.customer);//销毁互斥锁pthread_mutex_destroy(&mutex);   return 0;}




原创粉丝点击