自动重置事件内核对象
#include "stdafx.h" #include <windows.h> #include <iostream>
using namespace std;
DWORD WINAPI Tf() { cout<<"thread instantiated "<<endl;
HANDLE hEvent = OpenEvent(EVENT_ALL_ACCESS, FALSE, __T("MyEvent")); if (!hEvent) return -1;
for (char counter = 0; counter < 2; counter++) //char { WaitForSingleObject(hEvent, INFINITE); cout<<"Got The Single"<<endl; } CloseHandle(hEvent); cout<<"End of the Thread"<<endl; return 0; }
int main(){ // Create an Auto Reset Event which automatically reset to // Non Signalled state after being signalled HANDLE hEvent = CreateEvent(NULL, FALSE, FALSE, __T("MyEvent")); if (!hEvent) return -1;
DWORD Id; HANDLE hThrd = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)Tf, 0, 0, &Id); while(!hThrd) { CloseHandle(hThrd); return -1; } // Wait for a while before continuing. Sleep(1000);
for (char counter = 0; counter < 2; counter++) { // Signal the event SetEvent(hEvent); // wait for some time before giving another signal Sleep(2000); } // Wait for the Thread to Die WaitForSingleObject(hThrd, INFINITE); CloseHandle(hThrd); CloseHandle(hEvent); cout<<"End of Main .."<<endl;
system("pause"); return 0; }
手动重置事件内核对象
DWORD WINAPI Tf() { cout<<"thread instantiated "<<endl;
HANDLE hEvent = OpenEvent(EVENT_ALL_ACCESS, FALSE, __T("MyEvent")); if (!hEvent) return -1;
for (char counter = 0; counter < 2; counter++) //char { WaitForSingleObject(hEvent, INFINITE); // We need to reset the event since the event is manual reset // event ResetEvent(hEvent); cout<<"Got The Single"<<endl; } CloseHandle(hEvent); cout<<"End of the Thread"<<endl; return 0; }
int main(){ // Create an Manual Reset Event where events must be reset // manually to non signalled state HANDLE hEvent = CreateEvent(NULL, TRUE, FALSE, __T("MyEvent")); if (!hEvent) return -1;
DWORD Id; HANDLE hThrd = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)Tf, 0, 0, &Id); while(!hThrd) { CloseHandle(hThrd); return -1; } // Wait for a while before continuing. Sleep(1000);
for (char counter = 0; counter < 2; counter++) { // Signal the event SetEvent(hEvent); // wait for some time before giving another signal Sleep(2000); } // Wait for the Thread to Die WaitForSingleObject(hThrd, INFINITE); CloseHandle(hThrd); CloseHandle(hEvent); cout<<"End of Main .."<<endl;
system("pause"); return 0; }
|