// WaitForSingleObject.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <afxmt.h>
CEvent g_event;
void ThreadFunc1(LPVOID pParam)
{
::WaitForSingleObject(g_event,INFINITE);
for( int i = 0; i < 100; i++ )
{
printf("ThreadFunc1:%d\n", i);
}
}
void ThreadFunc2(LPVOID pParam)
{
for( int i = 0; i < 5; i++ )
{
printf("ThreadFunc2:%d\n", i);
Sleep(1000);
}
g_event.SetEvent();
}
int _tmain(int argc, _TCHAR* argv[])
{
DWORD m_ThreadID[2];
g_event.ResetEvent();
::CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ThreadFunc1,NULL,0,&m_ThreadID[0]);
::CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ThreadFunc2,NULL,0,&m_ThreadID[1]);
getchar();
}
本文通过一个C++示例程序介绍了如何使用线程同步机制来协调两个并发执行的线程。其中一个线程通过等待事件对象被设置来确保其在另一个线程执行特定操作后开始运行。
1578

被折叠的 条评论
为什么被折叠?



