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

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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值