1、生产者消费者问题用 vc+实现 悬最佳答案 #include#include#include#include#include/定义一些常量;/本程序允许的最大临界区数;#define MAX_BUFFER_NUM 10/秒到微秒的乘法因子;#define INTE_PER_SEC 1000/本程序允许的生产和消费线程的总数;#define MAX_THREAD_NUM 64/定义一个结构,记录在测试文件中指定的每一个线程的参数struct ThreadInfoint serial; /线程序列号char entity; /是 P 还是 Cdouble delay; /线程延迟int threa
2、d_requestMAX_THREAD_NUM; /线程请求队列int n_request; /请求个数;/全局变量的定义/临界区对象的声明,用于管理缓冲区的互斥访问;CRITICAL_SECTION PC_CriticalMAX_BUFFER_NUM; int Buffer_CriticalMAX_BUFFER_NUM; /缓冲区声明,用于存放产品;HANDLE h_ThreadMAX_THREAD_NUM; /用于存储每个线程句柄的数组;ThreadInfo Thread_InfoMAX_THREAD_NUM; /线程信息数组;HANDLE empty_semaphore; /一个信号量;
3、HANDLE h_mutex; /一个互斥量;DWORD n_Thread = 0; /实际的线程的数目;DWORD n_Buffer_or_Critical; /实际的缓冲区或者临界区的数目;HANDLE h_SemaphoreMAX_THREAD_NUM; /生产者允许消费者开始消费的信号量;/生产消费及辅助函数的声明void Produce(void *p);void Consume(void *p); bool IfInOtherRequest(int);int FindProducePositon();int FindBufferPosition(int);int main(void
4、)/声明所需变量;DWORD wait_for_all;ifstream inFile;/初始化缓冲区;for(int i=0;i n_Buffer_or_Critical;inFile.get();printf(“输入文件是:n“);/回显获得的缓冲区的数目信息;printf(“%d n“,(int) n_Buffer_or_Critical);/提取每个线程的信息到相应数据结构中;while(inFile)inFile Thread_Infon_Thread.serial;inFile Thread_Infon_Thread.entity;inFile Thread_Infon_Threa
5、d.delay;char c;inFile.get(c);while(c!=ninFile.get(c); n_Thread+; /回显获得的线程信息,便于确认正确性; for(j=0;jserial;m_delay = (DWORD)(ThreadInfo*)(p)-delay *INTE_PER_SEC);Sleep(m_delay);/开始请求生产printf(“Producer %2d sends the produce require.n“,m_serial);/确认有空缓冲区可供生产,同时将空位置数 empty 减 1;用于生产者和消费者的同步;wait_for_semaphore
6、 = WaitForSingleObject(empty_semaphore,-1);/互斥访问下一个可用于生产的空临界区,实现写写互斥;wait_for_mutex = WaitForSingleObject(h_mutex,-1);int ProducePos = FindProducePosition();ReleaseMutex(h_mutex);/生产者在获得自己的空位置并做上标记后,以下的写操作在生产者之间可以并发;/核心生产步骤中,程序将生产者的 ID 作为产品编号放入,方便消费者识别;printf(“Producer %2d begin to produce at positi
7、on %2d.n“,m_serial,ProducePos);Buffer_CriticalProducePos = m_serial;printf(“Producer %2d finish producing :n “,m_serial);printf(“ position %2d :%3d n“ ,ProducePos,Buffer_CriticalProducePos);/使生产者写的缓冲区可以被多个消费者使用,实现读写同步;ReleaseSemaphore(h_Semaphorem_serial,n_Thread,NULL);/消费者进程void Consume(void * p)/局
8、部变量声明;DWORD wait_for_semaphore,m_delay;int m_serial,m_requestNum; /消费者的序列号和请求的数目;int m_thread_requestMAX_THREAD_NUM;/本消费线程的请求队列;/提取本线程的信息到本地;m_serial = (ThreadInfo*)(p)-serial;m_delay = (DWORD)(ThreadInfo*)(p)-delay *INTE_PER_SEC);m_requestNum = (ThreadInfo *)(p)-n_request;for (int i = 0;ithread_req
9、uesti;Sleep(m_delay); /循环进行所需产品的消费for(i =0;ithread_requesti =-1;if(!IfInOtherRequest(m_thread_requesti)Buffer_CriticalBufferPos = -1;/标记缓冲区为空;printf(“Consumer%2d finish consuming %2d:n “,m_serial,m_thread_requesti);printf(“ position %2d :%3d n“ ,BufferPos,Buffer_CriticalBufferPos);ReleaseSemaphore(empty_semaphore,1,NULL); elseprintf(“Consumer %2d finish consuming product %2dn “,m_serial,m_thread_requesti);/离开临界区LeaveCriticalSection(8