事件对象。

    在用多线程编程时,往往会要求某线程执行完毕以后,再执行其他线程。或者要求对公共资源进行保护。这时我们的选择还是很多的:关键代码段(CriticalSection)、互斥体(mutex)、事件。你可以使用MFC封装的CEvent或者使用Windows API CreateEvent, 今天,我们来总结下Windows API 中事件的用法。

When the state of a manual-reset event object is signaled, it remains signaled until it is explicitly reset to nonsignaled by the ResetEvent function. Any number of waiting threads, or threads that subsequently begin wait operations for the specified event object, can be released while the object's state is signaled.

When the state of an auto-reset event object is signaled, it remains signaled until a single waiting thread is released; the system then automatically resets the state to nonsignaled. If no threads are waiting, the event object's state remains signaled.

   事件,分为人工重置事件和自动重置事件。为了实现线程的同步,我们应该用自动重置事件。

   使用事件通常分为5步:1.定义 2.创建事件 3.另一个线程等待 4.释放 5.关闭

#include <windows.h>
#include <iostream>
using namespace std;

DWORD WINAPI Fun1Proc(
  LPVOID lpParameter   // thread data
);

DWORD WINAPI Fun2Proc(
  LPVOID lpParameter   // thread data
);

int tickets=100;
//  1.定义
HANDLE g_hEvent;

void main()
{
	HANDLE hThread1;
	HANDLE hThread2;
	// 2.创建事件 
	g_hEvent=CreateEvent(NULL,FALSE,FALSE,"tickets");
	if(g_hEvent)
	{
		if(ERROR_ALREADY_EXISTS==GetLastError())
		{
			cout<<"only one instance can run!"<<endl;
			return;
		}
	}

	hThread1=CreateThread(NULL,0,Fun1Proc,NULL,0,NULL);
	hThread2=CreateThread(NULL,0,Fun2Proc,NULL,0,NULL);
	CloseHandle(hThread1);
	CloseHandle(hThread2);

    // 4.释放 
	SetEvent(g_hEvent);

	int a;
	cin>>a;

	// 5.关闭
	CloseHandle(g_hEvent);
}

DWORD WINAPI Fun1Proc(
  LPVOID lpParameter   // thread data
)
{
	while(TRUE)
	{
		// 3.另一个线程等待
		WaitForSingleObject(g_hEvent,INFINITE);
		if(tickets>0)
		{
			Sleep(1);
			cout<<"thread1 sell ticket : "<<tickets--<<endl;
			// 4.释放
			SetEvent(g_hEvent);
		}
		else
		{
			// 4.释放 
			SetEvent(g_hEvent);
			break;
		}
	}
	
	return 0;
}

DWORD WINAPI Fun2Proc(
  LPVOID lpParameter   // thread data
)
{
	
	while(TRUE)
	{
		WaitForSingleObject(g_hEvent,INFINITE);
		if(tickets>0)
		{
			Sleep(1);
			// 4.释放 
			SetEvent(g_hEvent);
			cout<<"thread2 sell ticket : "<<tickets--<<endl;
		}
		else
		{	// 4.释放 
			SetEvent(g_hEvent);
			break;
		}
	}
	
	return 0;
}



你可能感兴趣的:(thread,windows,object,null,fun,winapi)