//生产者消费者问题 //使用信号量和互斥量实现 //信号量用于同步:缓冲区有产品,消费者才能取;缓冲区有空位置,生产者才能放入。 //互斥量用于互斥:生产者和消费者不能同时访问缓冲区 // //缓冲区容量为4 #include <iostream> #include <Windows.h> //互斥量 HANDLE g_hMutex; //信号量 HANDLE g_hSemA; //表示空缓冲区个数 HANDLE g_hSemB; //非空缓冲区个数 //缓冲区 4个 int g_Buffer[4]; int g_i, g_j; DWORD WINAPI ProducterThreadFunc(PVOID pM) { int i; for(i = 1; i <= 10; i++) { //等待信号量>0, WaitForSingleObject(g_hSemA, INFINITE);//信号量-1 //等待互斥量被释放(触发) WaitForSingleObject(g_hMutex, INFINITE); g_Buffer[g_i] = i; std::cout<<"生产者从缓冲区 "<<g_i<<" 中放入产品:"<<g_Buffer[g_i]<<std::endl; g_i = (g_i + 1) % 4; //释放互斥量 ReleaseMutex(g_hMutex); //信号量+1,非空缓冲区个数+1 ReleaseSemaphore(g_hSemB, 1, NULL); } return 0; } DWORD WINAPI ConsumerFunc(PVOID pM) { while (true) { WaitForSingleObject(g_hSemB, INFINITE); //等待互斥量触发 WaitForSingleObject(g_hMutex,INFINITE); std::cout<<" "<<GetCurrentThreadId()<<" 号消费者从缓冲区 "<<g_j<<" 中拿出产品:"<<g_Buffer[g_j]<<std::endl; if(g_Buffer[g_j] == 10) { ReleaseMutex(g_hMutex); ReleaseSemaphore(g_hSemB, 1, NULL); break; } g_j = (g_j + 1) % 4; //释放互斥量 ReleaseMutex(g_hMutex); ReleaseSemaphore(g_hSemA, 1, NULL); } return 0; } int main() { g_i = 0; g_j = 0; //设置互斥量为触发状态(释放),第2个参数FALSE g_hMutex = CreateMutex(NULL, FALSE, NULL); //信号量 g_hSemA = CreateSemaphore(NULL, 4, 4, NULL);//4个空缓冲区 g_hSemB = CreateSemaphore(NULL, 0, 4, NULL); //线程 HANDLE hThread[3]; //生产者线程 hThread[0] = CreateThread(NULL, 0, ProducterThreadFunc, NULL, 0, NULL); //消费者线程 hThread[1] = CreateThread(NULL, 0, ConsumerFunc, NULL, 0, NULL); hThread[2] = CreateThread(NULL, 0, ConsumerFunc, NULL, 0, NULL); DWORD xxx = WaitForMultipleObjects(3, hThread, TRUE, INFINITE); std::cout<<std::endl<<"执行完成。 "<<std::endl; CloseHandle(hThread[0]); CloseHandle(hThread[1]); CloseHandle(g_hSemA); CloseHandle(g_hSemB); CloseHandle(g_hMutex); return 0; }
运行结果:
参考:http://blog.csdn.net/morewindows/article/details/7577591#reply