生产者消费者模拟程序
1.目标
编程实现生产者消费者或读写者的同步问题,目标掌握信号量实现进程同步及其应用
⒉基本要求
1) 利用线程模拟进程
2) 可视化显示模拟同步
⒊实现提示
设计在同一个进程地址空间内执行的多个线程。生产者线程和消费者线程。生产者线程生产物品,然后将物品放置在一个空缓冲区中供消费者线程消费。消费者线程从缓冲区中获得物品,然后释放缓冲区。生产者线程生产物品时,若无空缓冲区可用,生产者线程必须等待消费者线程释放出一个空缓冲区;消费者线程消费物品时,若无满的缓冲区,消费者线程将被阻塞,直到新的物品被生产出来。
需要使用如下信号量:
一个互斥信号量,用以阻止生产者线程和消费者线程同时操作缓冲区列表;
一个信号量,用于当缓冲区满时让生产者线程等待;
一个信号量,用于当缓冲区空时让消费者线程等待;
利用Windows提供的API函数,例如创建线程的函数CreateThread()、创建互斥对象函数CreateMutex()和创建信号量函数CreateSemaphore()等,自己上网或去图书馆查资料实现。
#include
#define bsize 2//缓冲区大小 #define p_count 3//生产者数 #define c_count 4//消费者数 int in=0; int out=0;
int buffer[bsize];
int productid=0;//产品标识 bool flag=true; HANDLE mutex; HANDLE full; HANDLE empty; void display(){
cout<<\ for(int i=0;i cout<<\ if(buffer[i]==0) cout<<\ <--可生产与此\ else cout<<\此产品可消费\ } cout< DWORD WINAPI producer(LPVOID para) {//生产者线程 int j= *(int*)para; while(flag) { WaitForSingleObject(empty,INFINITE); WaitForSingleObject(mutex,INFINITE); cout<<\ int productid=rand()0000+1; cout<<\ buffer[in]=productid; in=(in+1)%bsize; display(); Sleep(1200); ReleaseMutex(mutex); ReleaseSemaphore(full,1,NULL); } return 0; } DWORD WINAPI consumer(LPVOID para) {//消费者线程 int j=*(int*)para; while(flag) { WaitForSingleObject(full,INFINITE); WaitForSingleObject(mutex,INFINITE); cout<<\ productid=buffer[out]; cout<<\ buffer[out]=0; out=(out+1)%bsize; display(); Sleep(1200); ReleaseMutex(mutex); ReleaseSemaphore(empty,1,NULL); } return 0; } int main() { srand((unsigned) time(NULL)); mutex=CreateMutex(NULL,FALSE,NULL); full=CreateSemaphore(NULL,0,bsize,NULL); empty=CreateSemaphore(NULL,bsize,bsize,NULL); const int thread_count=p_count+c_count; DWORD p[p_count]; DWORD c[c_count]; HANDLE threads[thread_count]; cout<<\ cout<<\ 欢迎光临生产者消费者模拟程序\ cout<<\ 本程序模拟3个生产者4个消费者,缓冲区大小为2\ cout<<\ 要结束本程序,请按Enter键!\ cout<<\ for(int i=0;i for(i=0;i threads[i]=CreateThread(NULL,0,producer,&i,0,&p[i]); if(threads[i]==NULL) return -1;} for(int t=0;t threads[p_count+t]=CreateThread(NULL,0,consumer,&t,0,&c[t]); if(threads[t]==NULL) return -1;} while(flag){ if(getchar()) flag=false; } return 0; } 百度搜索“77cn”或“免费范文网”即可找到本站免费阅读全部范文。收藏本站方便下次阅读,免费范文网,提供经典小说教育文库生产者消费者模拟程序在线全文阅读。
相关推荐: