现在的位置: 首页 > 综合 > 正文

c++事件内核对象(event)进程间激活

2013年10月12日 ⁄ 综合 ⁄ 共 2099字 ⁄ 字号 评论关闭

         此文主要说明的是,c++中创建的一个事件内核对象可以在不同的程序(进程)间共用,也就是说多个程序可以处理同一个事件对象。可以使用此事件对象实现进程间的同步。

        关于CreateEvent说明,可参见c++中CreateEvent函数解析(2)

        当不同的进程间需要同步一些数据,例如只有进程1中的数据准备好时,进程2中的一个计算函数才能启用,这样可以保持数据同步,所以可以使用设置事件的信号的有无实现进程间的激活。

        在《c++中CreateEvent函数解析(2)》中,强调一下下面的细节:

         msdn上关于CreateEvent函数中参数bManualReset参数取值:手动重置和自动重置。关于其不同: 

         When the state of a manual-reset event object is signaled, it remains signaled until it is explicitly reset to nonsignaled by theResetEvent 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. 

        翻译如下:

      当一个手动复原的事件对象的状态被置为有信号状态时,该对象将一直保持有信号状态,直至明确调用ResetEvent函数将其置为无符号状态。当事件对象被设置为有信号状态时,任何数量的等待线程或者随后等待的线程都会被释放。
    当一个自动复原事件对象的状态被设置为有信号状态时,该对象一直保持有信号状态,直至一个单等待线程被释放;系统然后会自动重置对象到无信号状态。

事件1进程(Event1.exe)

#include <iostream>
#include <windows.h>
#include <string>

using namespace std;

#define EventName "eventName"

int main(int argc, char* argv[])
{
	HANDLE handle = CreateEvent(NULL,FALSE, FALSE,EventName);
	if (handle != NULL)
	{
		int count = 0;
		while (count < 10)
		{	
			WaitForSingleObject(handle,INFINITE);
			cout<<"EVENT1有信号了:"<<++count<<endl;
			Sleep(2000);
			ResetEvent(handle);
		}
	}
	return 0;
}

   从程序中此进程中创建了一个名为eventName的事件,从参数中设置可以看出,此事件是手动重置并且初始化的时候为无信号的。

   然后是一个while循环,通过WaitForSingleObjet函数等待此事件为有信号,这样才能打印出下面的信息。启动此进程的时候,进程会一直等待。

    事件2进程(Event2.exe)

     

#include <iostream>
#include <windows.h>
#include <string>

using namespace std;

#define EventName "eventName"

int main(int argc, char* argv[])
{
	HANDLE handle = OpenEvent(EVENT_ALL_ACCESS,NULL,EventName);
	if (handle != NULL)
	{
		int count = 0;
		while (count < 10)
		{	
			SetEvent(handle);
			cout<<"EVENT2有信号了:"<<++count<<endl;
			Sleep(2000);
		}
	}
	return 0;
}

    从程序中可以看出,此进程没有创建新的进程,而是打开一个进程名为eventName的事件,如果没有此名字的事件,则程序会直接退出。

    如果此时,我们已经运行Event1.exe,那么此进程会找到这个事件,执行下面的SetEvent函数,这样事件变为有信号状态。

    此时,Event1.exe的WaitForSingleObject函数检测到事件为有信号状态,打印信息,同时Event2.exe无条件的打印。

     运行结果如下:

   

      

      关于CreateEvent相关,请参考本博:

      c++CreateEvent函数在多线程中使用及实例


抱歉!评论已关闭.