#include "stdafx.h" #include <iostream> #include <Windows.h> #include <process.h> using namespace std; int buffer[4]; int iCountOfProduct=10; HANDLE hSemaphoreFull; HANDLE hSemaphoreEmpty; int gi=0; int gj=0; CRITICAL_SECTION g_cs; unsigned int __stdcall Producter(LPVOID p) { for(int i=1;i<=iCountOfProduct;i++) { WaitForSingleObject(hSemaphoreEmpty,INFINITE); EnterCriticalSection(&g_cs); buffer[gi]=i; cout<<"生产者放入 "<<"缓冲池:"<<gi<<"数据:"<<buffer[gi]<<endl; gi=(gi+1)%4; LeaveCriticalSection(&g_cs); ReleaseSemaphore(hSemaphoreFull,1,NULL); } printf("生产者完成任务,线程结束运行 "); return 0; } unsigned int __stdcall Customer(LPVOID p) { while(true) { WaitForSingleObject(hSemaphoreFull,INFINITE); EnterCriticalSection(&g_cs); cout<<"消费者读取 " <<"缓冲池:"<<gj<<"数据:"<<buffer[gj]<<endl; if (buffer[gj] == iCountOfProduct)//结束标志 { LeaveCriticalSection(&g_cs); //通知其它消费者有新数据了(结束标志) ReleaseSemaphore(hSemaphoreFull, 1, NULL); break; } gj=(gj+1)%4; LeaveCriticalSection(&g_cs); ReleaseSemaphore(hSemaphoreEmpty,1,NULL); } printf(" 编号为%d的消费者收到通知,线程结束运行 ", GetCurrentThreadId()); return 0; } void main() { HANDLE hThread[3]; InitializeCriticalSection(&g_cs); hSemaphoreFull=CreateSemaphore(NULL,0,4,NULL); hSemaphoreEmpty=CreateSemaphore(NULL,4,4,NULL); hThread[0]=(HANDLE)_beginthreadex(NULL,0,Producter,NULL,0,0); hThread[1]=(HANDLE)_beginthreadex(NULL,0,Customer,NULL,0,0); hThread[2]=(HANDLE)_beginthreadex(NULL,0,Customer,NULL,0,0); WaitForMultipleObjects(3,hThread,TRUE,INFINITE); for(int i=0;i<3;i++) { CloseHandle(hThread[i]); } CloseHandle(hSemaphoreFull); CloseHandle(hSemaphoreEmpty); }