在自己主动重置事件对象中,当WaitSingleObject/WaitForMultipleObjects接收到SetEvent发送过来的信号后则返回WAIT_OBJECT_0,此时操作系统(待定)自己主动重置等待的事件对象(即自己主动将其设置为无信号状态。不管何时通过SetEvent发送过来的信号,仅仅要未被接收到均不会被自己主动重置。但在未被接收之前能够调用ResetEvent手动重置等待的事件对象,此时等待的事件对象为无信号状态)。在手动重置事件对象中,当WaitSingleObject/WaitForMultipleObjects接收到SetEvent发送过来的信号后则返回WAIT_OBJECT_0,此时须要调用ResetEvent手动重置等待的事件对象(即手动将其设置为无信号状态)。
#include <windows.h> #include <iostream> using namespace std; DWORD WINAPI ThreadProc(LPVOID lpParam); DWORD WINAPI ThreadProc2(LPVOID lpParam); DWORD g_dwThreadID; DWORD g_dwThreadID2; UINT g_nTickets = 300; HANDLE g_hEvent = NULL; int main(int argc, char* argv[]) { cout << "Main thread is running." << endl; HANDLE hHandle = CreateThread(NULL, 0, ThreadProc, NULL, 0, &g_dwThreadID); HANDLE hHandle2 = CreateThread(NULL, 0, ThreadProc2, NULL, 0, &g_dwThreadID2); CloseHandle(hHandle); CloseHandle(hHandle2); g_hEvent = CreateEvent(NULL, FALSE, TRUE, NULL); Sleep(4000); system("pause"); return 0; } DWORD WINAPI ThreadProc(LPVOID lpParam) { // cout << "No." << g_dwThreadID << " thread is running." << endl; while (TRUE) { WaitForSingleObject(g_hEvent, INFINITE); if (g_nTickets > 0) { Sleep(1); cout << "No.1-" << g_dwThreadID << " sell ticket : " << g_nTickets << endl; g_nTickets--; SetEvent(g_hEvent); } else { break; } } return 0; } DWORD WINAPI ThreadProc2(LPVOID lpParam) { // cout << "No." << g_dwThreadID2 << " thread is running." << endl; while (TRUE) { WaitForSingleObject(g_hEvent, INFINITE); if (g_nTickets > 0) { Sleep(1); cout << "No.2-" << g_dwThreadID2 << " sell ticket : " << g_nTickets << endl; g_nTickets--; SetEvent(g_hEvent); } else { break; } } return 0; }