文档详情

OS实验6——信号量.docx

发布:2017-12-16约4.44千字共7页下载文档
文本预览下载声明
实验六 信号量一、实验内容(1)生产者/消费者问题:在windows和linux操作系统上,利用各自操作系统提供的mutex和信号量机制,实现生产者/消费者问题。具体要求见“Operating System Concepts(Seventh Edition)”Chapter 6后的project。(2)利用信号量解决读者——写者问题(选做)。二、实验目的通过实验,熟练掌握进程同步和互斥算法,理解生产者/消费者问题;掌握windows和linux中多进程/线程的同步互斥方法的使用。三、设计思路1、创建三个信号量:mutex,full,empty。2、主程序分别创建10个生产者线程和10个消费者线程。3、生产者线程:睡眠一段随机时间;向缓冲区插入一个随机数。4、消费者线程:睡眠一段随机时间;从缓冲区内取出一项。5、主程序睡眠一段时间后结束整个程序。四、源程序及注释1、windows#include windows.h#include string.h#include time.h#include stdlib.h#include stdio.h#define BUFFER_SIZE 5int buffer[BUFFER_SIZE];intcnt=0;//现有产品数量//定义并初始化信号量HANDLE mutex,empty,full;void init(){mutex=CreateMutex(NULL,FALSE,NULL);empty=CreateSemaphore(NULL,5,5,NULL);full=CreateSemaphore(NULL,0,5,NULL);}intinsert_item(intitem,int order){//向缓冲插入一个随机量int flag=-1;WaitForSingleObject(empty,INFINITE);WaitForSingleObject(mutex,INFINITE);//临界区if (cntBUFFER_SIZE){buffer[cnt++]=item;flag=0;//插入成功printf(producer %d produced %d\n,order,cnt);}ReleaseMutex(mutex);ReleaseSemaphore(full,1,NULL);return flag;}intremove_item(int item,int order){//删除缓冲区最后一个量int flag=-1;WaitForSingleObject(full,INFINITE);WaitForSingleObject(mutex,INFINITE);//临界区if (cnt0){item=buffer[cnt-1];buffer[cnt-1]=0;flag=0;printf(consumer %d consumed %d\n,order,cnt);cnt--;}ReleaseMutex(mutex);ReleaseSemaphore(empty,1,NULL);return flag;}DWORD WINAPI producer(void *param){srand((unsigned)time(NULL));int random;while (true){Sleep((rand()%10+1)*1000);random=rand()%50+1;if (insert_item(random,(DWORD)param))printf(report error condition\n);}}DWORD WINAPI consumer(void *param){srand((unsigned)time(NULL));int random;while (true){Sleep((rand()%10+1)*1000);if (remove_item(random,(DWORD)param))printf(report error condition\n);}}int main(intargc,char *argv[]){init();//主线程睡眠时间static constintsleepTime=10000;//生产者线程数量static constintproducerThs=10;//消费者线程数量static constintconsumerThs=10;//缓存区初始化memset(buffer,0,sizeof buffer);DWORD ProducerThreadId[producerThs];DWORD ConsumerThreadId[consumerThs];HANDLE ProducerThreadHandles[producerThs];HANDLE C
显示全部
相似文档