1 //生产者消费者问题 2 //使用事件和临界区实现 3 //缓冲区只能放一个产品 4 5 #include <iostream> 6 #include <Windows.h> 7 8 9 //临界区 10 CRITICAL_SECTION g_cs; 11 //事件 12 HANDLE g_hEventBufferEmpty, g_hEventBufferFull; 13 //缓冲区,只能放一个产品 14 int g_Buffer; 15 16 DWORD WINAPI ProducterThreadFunc(PVOID pM) 17 { 18 int i; 19 for(i = 1; i <= 10; i++) 20 { 21 WaitForSingleObject(g_hEventBufferEmpty, INFINITE); 22 23 EnterCriticalSection(&g_cs); 24 g_Buffer = i; 25 std::cout<<"生产者放入产品:"<<i<<std::endl; 26 LeaveCriticalSection(&g_cs); 27 28 SetEvent(g_hEventBufferFull); 29 } 30 return 0; 31 } 32 DWORD WINAPI ConsumerFunc(PVOID pM) 33 { 34 int i; 35 for(i = 1; i <= 10; i++) 36 { 37 WaitForSingleObject(g_hEventBufferFull, INFINITE); 38 39 EnterCriticalSection(&g_cs); 40 std::cout<<" 消费者拿出产品:"<<g_Buffer<<std::endl; 41 LeaveCriticalSection(&g_cs); 42 43 44 SetEvent(g_hEventBufferEmpty); 45 } 46 return 0; 47 } 48 int main() 49 { 50 //初始化临界区 51 InitializeCriticalSection(&g_cs); 52 //事件 53 //开始设置缓冲区为空的事件触发,第3个参数 54 g_hEventBufferEmpty = CreateEvent(NULL, FALSE, TRUE, NULL); 55 //设置缓冲区满的事件未触发 56 g_hEventBufferFull = CreateEvent(NULL, FALSE, FALSE, NULL); 57 58 //线程 59 HANDLE hThread[2]; 60 hThread[0] = CreateThread(NULL, 0, ProducterThreadFunc, NULL, 0, NULL); 61 hThread[1] = CreateThread(NULL, 0, ConsumerFunc, NULL, 0, NULL); 62 WaitForMultipleObjects(2, hThread, TRUE, INFINITE); 63 64 std::cout<<std::endl<<"执行完成。 "<<std::endl; 65 CloseHandle(hThread[0]); 66 CloseHandle(hThread[1]); 67 68 CloseHandle(g_hEventBufferEmpty); 69 CloseHandle(g_hEventBufferFull); 70 DeleteCriticalSection(&g_cs); 71 return 0; 72 }