前面的一个帖子说了如何实现线程的同步,利用的是信号量来实现,关键的函数是:CreateMutex和ReleaseMutex函数。
下面,看看事件方式如何实现同步吧!
代码:
#include <windows.h>
#include <iostream>
using namespace std;

DWORD WINAPI Fun1Proc(LPVOID param);
DWORD WINAPI Fun2Proc(LPVOID Param);

int time;
HANDLE events;

void main()


{
HANDLE thread1,thread2;
thread1 = CreateThread(NULL,0,Fun1Proc,NULL,0,NULL);
thread2 = CreateThread(NULL,0,Fun2Proc,NULL,0,NULL);
CloseHandle(thread1);
CloseHandle(thread2);
events = CreateEvent(NULL,FALSE,FALSE,NULL);
SetEvent(events);
Sleep(4000);
CloseHandle(events);
}
DWORD WINAPI Fun1Proc(LPVOID param)


{

while(1)
{
WaitForSingleObject(events,INFINITE);

if(time <= 20)
{
Sleep(1);
cout << "线程1运行第" << time++ << "次" << endl;
}
else
break;
SetEvent(events);
}
return 0;
}

DWORD WINAPI Fun2Proc(LPVOID param)


{

while(1)
{
WaitForSingleObject(events,INFINITE);

if(time <= 20)
{
Sleep(1);
cout << "线程2运行第" << time++ << "次" << endl;
}
else
break;
SetEvent(events);
}
return 0;
}
从代码上可以看到,除了对应的函数不同以外,其他的方式都是相同的,即:
对应的函数从CreateMutex变成了CreateEvent,而释放资源则由ReleaseMutex变为SetEvent了。
效果相同,输出都是:
线程1运行第0次
线程2运行第1次
线程1运行第2次
线程2运行第3次
线程1运行第4次
线程2运行第5次
线程1运行第6次
线程2运行第7次
线程1运行第8次
线程2运行第9次
线程1运行第10次
线程2运行第11次
线程1运行第12次
线程2运行第13次
线程1运行第14次
线程2运行第15次
线程1运行第16次
线程2运行第17次
线程1运行第18次
线程2运行第19次
线程1运行第20次
Press any key to continue
posted on 2010-02-09 18:54
deercoder 阅读(1054)
评论(0) 编辑 收藏 引用