CreateEvent

  1. lpEventAttributes一般为NULL
  2. bManualReset, 创建的Event是自动复位还是人工复位.如果true,人工复位,一旦该Event被设置为有信号,则它一直会等到ResetEvent()API被调用时才会恢复为无信号.如果为false,Event被设置为有信号,则当有一个wait到它的Thread时,该Event就会自动复位,变成无信号.如果想 在每次调用WaitForSingleObject 后让WINDOWS为您自动地把事件地状态恢复为”无信号”状态,必须把该参数设为FALSE,否则,您必须每次调用ResetEvent函数来清除事件 的信号。
  3. bInitialState, 初始状态,true,有信号,false无信号
  4. lpName, 事件对象的名称。您在OpenEvent函数中可能使用。

一个Event被创建以后,可以用OpenEvent()API来获得它的Handle,用CloseHandle()来关闭它,用SetEvent()或PulseEvent()来设置它使其有信号,用ResetEvent()来使其无信号,用WaitForSingleObject()或WaitForMultipleObjects()来等待其变为有信号.

HANDLE CreateEvent(
    LPSECURITY_ATTRIBUTES     lpEventAttributes, 
    BOOL     bManualReset,                                           
    BOOL     bInitialState,                                         
    LPCTSTR     lpName       
);   

HANDLE m_hResponseEvent = CreateEvent(NULL, FALSE, FALSE, NULL);

SetEvent & WaitForSingleObject

通过SetEvent设置信号,使WaitForSingleObject能检测到信号。当检测到信号时,程序继续执行,当没有信号时,程序等待信号,线程进入阻塞状态。

DWORD WINAPI thread1fun(LPVOID);
DWORD WINAPI thread2fun(LPVOID);

int tickets = 20;
HANDLE hEvent;

int main()
{
    HANDLE hthread1, hthread2;
    hEvent = CreateEvent(NULL, FALSE, FALSE, _T("tickets"));
    if (hEvent)
    {
        SetEvent(hEvent);
        hthread1 = CreateThread(NULL, 0, thread1fun, NULL, 0, NULL);
        hthread2 = CreateThread(NULL, 0, thread2fun, NULL, 0, NULL);

        Sleep(10000);
        if (hthread1 ) {
            CloseHandle(hthread1);
        }

        if (hthread2) {
            CloseHandle(hthread2);
        }

        CloseHandle(hEvent);
    }   
    return 0;
}

DWORD WINAPI thread1fun(LPVOID lpParameter)
{
    while (1)
    {
        WaitForSingleObject(hEvent, INFINITE);
        if (tickets > 0)
        {
            std::cout << "thread 1: " << tickets-- << std::endl;
            SetEvent(hEvent);
            Sleep(50);
        }
        else
            break;        
    }
    return 0;
}

WaitForSingleObject

返回值:

  1. WAIT_OBJECT_0=0,The state of the specified object is signaled.
  2. WAIT_TIMEOUT=0x00000102L, The time-out interval elapsed, and the object’s state is nonsignaled.
  3. WAIT_FAILED=(DWORD)0xFFFFFFFF, The function has failed. To get extended error information, call GetLastError.
  4. WAIT_ABANDONED=0x00000080L, The specified object is a mutex object that was not released by the thread that owned the mutex object before the owning thread terminated. Ownership of the mutex object is granted to the calling thread and the mutex state is set to nonsignaled.

     DWORD WaitForSingleObject(
       [in] HANDLE hHandle,
       [in] DWORD  dwMilliseconds
     );
    

WaitForMultipleObjects

进程在该函数处等待(即暂停在此处),直到被指定的其中一个或者全部信号触发 也或者超过了最长等待时间时,跳出该函数,继续向下执行代码。