<<Windows核心编程(第五版)>>第九章用内核对象进行线程同步:9.3事件内核对象

来源:互联网 发布:淘宝不可以微信付款吗 编辑:程序博客网 时间:2024/05/16 06:25

9.3 事件内核对象

//Create a global handle to a manual-reset,nonsignaled event.

HANDLE g_hEvent;

int WINAPI _tWinMain(...) {

g_hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);


//Spawn 3 new threads.

HANDLE hThread[3];

DWORD dwThreadID;

hThead[0] = _beginthreadex(NULL,0,WordCount,NULL,0,&dwThreadID);

hThead[1] = _beginthreadex(NULL,0,SpellCheck,NULL,0,&dwThreadID);

hThead[2] = _beginthreadex(NULL,0,GrammarCheck,NULL,0,&dwThreadID);


OpenFileAndReadContentsIntoMemory(...);


//Allow all 3 threads to access the memory.

SetEvent(g_hEvent);

...

}


DWORD WINAPI WordCount(PVOID pvParam){

//Wait until the file's data is in memory.

WaitForSignleObject(g_hEventNITE);

//Access the memory block.

...return(0);

}


DWORD WINAPI SpellCheck(PVOID pvParam){

//Wait until the file's data is in memory.

WaitForSignleObject(g_hEventNITE);

//Access the memory block.

...return(0);

}

DWORD WINAPI GrammarCheck(PVOID pvParam){

//Wait until the file's data is in memory.

WaitForSignleObject(g_hEventNITE);

//Access the memory block.

...return(0);

}

如果是手动重置事件则一旦主线程将数据准备完毕,它会调用SetEvent来触发事件。系统会使三个次要线程都变成可调度状态;如果是自动重置事件,则需要在每个次要线程里调用SetEvent(g_hEvent)来保证三个次要线程都会被触发到。

一个简单的例子:

// Handshake.cpp : Defines the entry point for the console application.
//


#include "stdafx.h"
#include <Windows.h>
#include <tchar.h>


//////////////////////////////////////////////////////////////////////////
HANDLE g_hevtRequestSubmitted;
HANDLE g_hevtResultReturned;


//////////////////////////////////////////////////////////////////////////
DWORD WINAPI DeputyThread(PVOID pvParam)
{
WaitForSingleObject(g_hevtRequestSubmitted,INFINITE);
MessageBoxA(0,"got it","DeputyThread",0);
SetEvent(g_hevtResultReturned);


return 0;
}


//////////////////////////////////////////////////////////////////////////
int _tmain(int argc, _TCHAR* argv[])
{
// Create & initialize the 2 non-signaled, auto-reset events
g_hevtRequestSubmitted = CreateEvent(NULL,FALSE,FALSE,NULL);
g_hevtResultReturned = CreateEvent(NULL,FALSE,FALSE,NULL);


// Spawn the deputyThread thread
DWORD dwDeputyThreadID;
HANDLE hThreadDeputy = CreateThread(NULL,0,DeputyThread,NULL,0,&dwDeputyThreadID);


MessageBoxA(0,"begin","event",0);
SetEvent(g_hevtRequestSubmitted);
WaitForSingleObject(g_hevtResultReturned,INFINITE);
MessageBoxA(0,"end","event",0);

CloseHandle(hThreadDeputy);
CloseHandle(g_hevtRequestSubmitted);
CloseHandle(g_hevtResultReturned);


return 0;
}


原创粉丝点击