windows_39_Thread_Event 线程 - 事件
// windows_39_Thread_Event.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "windows.h"
HANDLE g_hEvent = NULL;
HANDLE g_hEvent2 = NULL;
//发送线程
DWORD WINAPI ThreadSend( LPVOID pParam )
{
while (1)
{
SetEvent( g_hEvent );
Sleep( 500 );
SetEvent( g_hEvent2 );
Sleep( 500 );
}
return 0;
}
//接收线程
DWORD WINAPI ThreadRecv( LPVOID pParam )
{
while (1)
{
//等候事件通知
WaitForSingleObject( g_hEvent,INFINITE);
printf( "Hello Event: %p\n", g_hEvent );
}
return 0;
}
DWORD WINAPI ThreadRecv2( LPVOID pParam )
{
while (1)
{
//等候事件通知
WaitForSingleObject( g_hEvent2,INFINITE);
printf( "Hello Event: %p\n", g_hEvent );
Sleep( 500 );
}
return 0;
}
//线程创建
void Create( )
{
DWORD nThreadID = 0;
HANDLE hThread[3] = { NULL };
//创建触发事件
hThread[0] = CreateThread( NULL, 0, ThreadSend, NULL, 0, &nThreadID );
hThread[1] = CreateThread( NULL, 0, ThreadRecv, NULL, 0, &nThreadID );
hThread[2] = CreateThread( NULL, 0, ThreadRecv2, NULL, 0, &nThreadID );
}
int _tmain(int argc, _TCHAR* argv[])
{
//创建自动重置事件
g_hEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
//创建手动重置事件
g_hEvent2 = CreateEvent( NULL, TRUE, FALSE, NULL );
Create( );
getchar( );
//关闭事件
CloseHandle( g_hEvent );
CloseHandle( g_hEvent2 );
return 0;
}
时间: 2024-10-09 13:10:45