CreateEvent例子

#include <windows.h>
#include <iostream>
#include <string>
#include <vector>
using namespace std;

//通过事件得知另一个线程的内部状态
//例:线程内部有三种状态:起床 吃饭 上班
HANDLE getupHandle;
HANDLE breakfastHandle;
HANDLE workHandle;

vector<string> stateTexts;
DWORD WINAPI Worker(LPVOID n);

int main()
{
	stateTexts.reserve(3);
	getupHandle = CreateEvent(NULL, TRUE, FALSE, NULL);
	breakfastHandle = CreateEvent(NULL, TRUE, FALSE, NULL);
	workHandle = CreateEvent(NULL, TRUE, FALSE, NULL);
	
	DWORD threadId;
	HANDLE threadHandle = CreateThread(NULL,
			0,
			Worker,
			0,
			0,
			&threadId);

	WaitForSingleObject(getupHandle, INFINITE);
	cout << stateTexts[0] << endl;
	system("pause");
	WaitForSingleObject(breakfastHandle, INFINITE);
	cout << stateTexts[1] << endl;
	system("pause");
	WaitForSingleObject(workHandle, INFINITE);
	cout << stateTexts[2] << endl;

	CloseHandle(threadHandle);
	CloseHandle(getupHandle);
	CloseHandle(breakfastHandle);
	CloseHandle(workHandle);

	system("pause");
}

DWORD WINAPI Worker(LPVOID n)
{
	stateTexts.push_back("GetUp");
	SetEvent(getupHandle);
	stateTexts.push_back("breakfast");
	SetEvent(breakfastHandle);
	stateTexts.push_back("Work");
	SetEvent(workHandle);
	return 0;
}

结果

etUp
请按任意键继续. . .
reakfast
请按任意键继续. . .
ork
请按任意键继续. . .

你可能感兴趣的:(null,System,include,winapi)