欢迎来到天天文库
浏览记录
ID:59158980
大小:21.08 KB
页数:12页
时间:2020-09-15
《生产者消费者.docx》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、实验课程:操作系统实验实验编号:实验名称:生产者消费者算法实验人员:年级专业学号姓名实验日期:上交日期:实验室:实验评价:实验成绩:评定日期:指导教师:一、目的和要求生产者消费者算法是操作系统中很重要的同步算法,通过本实验加深对互斥信号量和同步信号量的理解,掌握如何用信号量机制实现生产者消费者之间的同步算法。二、实验内容运用高级语言模拟实现生产者消费者算法,要求实现对缓冲池的互斥访问和生产者进程与消费者进程之间的同步,观察程序的运行情况并分析执行结果。三、实验环境1.PC微机。2.Windows操作系统。3.C/C++/
2、VB开发集成环境。四、实验结果1.程序源代码:生产者&消费者如下图:#include#include#include#include#include#include#include#include#defineBUFFER_SIZE5typedefintbuffer_item;//semaphoressem_tempty,full,mutex;//buff
3、erbuffer_itembuffer[BUFFER_SIZE];intin,out;//存储数据的结构体structdata{intid;intopTime;intlastTime;intproductId;};//有限缓存插入--生产intinsert_item(buffer_itemitem){/*insertitemintobuffer*/buffer[out]=item;out=(out+1)%BUFFER_SIZE;return0;}//有限缓存删除--消费intremove_item(buffer_item
4、*item){/*removeanobjectfrombufferandthenplaceitinitem*/*item=buffer[in];in=(in+1)%BUFFER_SIZE;return0;}//生产者void*producer(void*param){intproductId=((structdata*)param)->productId;intlastTime=((structdata*)param)->lastTime;intopTime=((structdata*)param)->opTime;in
5、tid=((structdata*)param)->id;free(param);sleep(opTime);sem_wait(&empty);sem_wait(&mutex);/*criticalsection*///addaiteminsert_item(productId);sleep(lastTime);printf("Thread%d:Producerproduce%d",id,productId);sem_post(&mutex);sem_post(&full);pthread_exit(0);}//消费
6、者void*consumer(void*param){intlastTime=((structdata*)param)->lastTime;intopTime=((structdata*)param)->opTime;intid=((structdata*)param)->id;free(param);sleep(opTime);sem_wait(&full);sem_wait(&mutex);/*criticalsection*///removeaitembuffer_itemitem;remove_item(&ite
7、m);sleep(lastTime);printf("Thread%d:Consumerconsume%d",id,item);sem_post(&mutex);sem_post(&empty);pthread_exit(0);}intmain(){//pthreadpthread_ttid;//thethreadidentifierpthread_attr_tattr;//setofthreadattributes/*getthedefaultattributes*/pthread_attr_init(&attr)
8、;//initialthesemaphoressem_init(&mutex,0,1);sem_init(&empty,0,BUFFER_SIZE);sem_init(&full,0,0);in=out=0;intid=0;while(scanf("%d",&id)!=EOF){charrole;//producer
此文档下载收益归作者所有