扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
作者:51cto 2007年10月14日
关键字:
在本页阅读全文(共3页)
// To add a declaration for the "new" operator:
class ObjectWithEvents : public IObjectWithEvents
{
public:void * operator new(unsigned int);
};
// To include an additional header for the Initializer class:
#include "Initializer.h"
// To overload the operator "new":
void * ObjectWithEvents::operator new(unsigned int)
{return ms_pObjectWithEvents;
}
// Then, FireEvent is completely changed:
void ObjectWithEvents::FireEvent()
{// We need to serialize all access to the collection by more than one processint iRetVal = Initializer::LockMutex();
if (0 != iRetVal){return;}
pid_t pid = getpid();
// iterate through the collection and fire only events belonging to the current processfor (long i = 0; i < m_npEI; i++){// Check whether the handler belongs to the current process.if (pid != m_alPID[i]){continue;}
//Recheck for NULLif (0 != m_apEI[i]){m_apEI[i]->OnEvent(pid, "");}}
// release the mutexif ((0 == iRetVal) && (0 != Initializer::UnlockMutex())){// Deal with error.}
return;
}
// The following are changes to ObjectWithEvents::AddEventHandler():
// 1. Before accessing the collection, we lock the mutex:
int bRetVal = Initializer::LockMutex();
if (0 != bRetVal)
{return false;
}
// 2. After accessing the collection, we release the mutex:
if ((0 == bRetVal) && (0 != Initializer::UnlockMutex()))
{// Deal with error.
}
|
#ifndef __Initializer_H__
#define __Initializer_H__
class Initializer
{
public : int m_shmid; static Initializer ms_Initializer; Initializer();
static pthread_mutex_t ms_mutex; static int LockMutex(); static int UnlockMutex();
};
#endif // __Initializer_H__
|
#include |
如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。