C++线程同步之事件(生产者与消费者问题)
#include <windows.h> #include <stdio.h> HANDLE g_hSet = NULL; HANDLE g_hClear = NULL; HANDLE hThread[2] = { NULL }; int g_Max = 10; int g_Number = 0; // 生产者线程 DWORD WINAPI ThreadProc1(LPVOID lpParameter) { for (int i = 0; i < g_Max; i++) { WaitForSingleObject(g_hSet, INFINITE); g_Number = 1; DWORD id = GetCurrentThreadId(); printf("生产者%d将数据%d放入缓冲区!\n", id, g_Number); SetEvent(g_hClear); } return 0; } // 消费者线程 DWORD WINAPI ThreadProc2(LPVOID lpParameter) { for (int i = 0; i < g_Max; i++) { WaitForSingleObject(g_hClear, INFINITE); g_Number = 0; DWORD id = GetCurrentThreadId(); printf("---消费者%d将数据%d放入缓冲区!\n", id, g_Number); SetEvent(g_hSet); } return 0; } int main() { g_hSet = ::CreateEvent(NULL, FALSE, TRUE, NULL); g_hClear = ::CreateEvent(NULL, FALSE, FALSE, NULL); hThread[0] = CreateThread(0, 0, ThreadProc1, 0, 0, 0); hThread[1] = CreateThread(0, 0, ThreadProc2, 0, 0, 0); WaitForMultipleObjects(2, hThread, TRUE, -1); CloseHandle(hThread[0]); CloseHandle(hThread[1]); CloseHandle(g_hClear); CloseHandle(g_hSet); getchar(); return 0; }
临界区与互斥体是不能解决线程同步问题的,只能解决互斥问题,但是事件既可以解决互斥问题,又可以解决线程同步问题。