/**
* SyncObject - The class is a wrapper of Critical section object to provide
* synchronization for thread pool.
*/
class SyncObject
{
public:
// Constructor
SyncObject()
{
::InitializeCriticalSection( &m_stCriticalSection );
}
// Destructor
~SyncObject()
{
::DeleteCriticalSection( &m_stCriticalSection );
}
// Lock critical section.
bool Lock()
{
::EnterCriticalSection( &m_stCriticalSection );
return true;
}
// Unlock critical section.
bool Unlock()
{
::LeaveCriticalSection( &m_stCriticalSection );
return true;
}
/* private:
SyncObject( const SyncObject& );
SyncObject& operator = ( const SyncObject& );*/
private:
// Critical section object.
CRITICAL_SECTION m_stCriticalSection;
};
/**
* AutoLock - This class own synchronization object during construction and
* release the ownership during the destruction.
*/
class AutoLock
{
public:
/**
* Parameterized constructor
*
* @param LockObj_i - Synchronization object.
* @return Nil
* @exception Nil
* @see Nil
* @since 1.0
*/
AutoLock( SyncObject& LockObj_i ) : m_pSyncObject(&LockObj_i)
{
if( NULL != m_pSyncObject )
{
m_pSyncObject->Lock();
}
}
/**
* Destructor.
*
* @param Nil
* @return Nil
* @exception Nil
* @see Nil
* @since 1.0
*/
~AutoLock()
{
if( NULL != m_pSyncObject )
{
m_pSyncObject->Unlock();
m_pSyncObject = NULL;
}
}
private:
SyncObject* m_pSyncObject;
};
使用例子:
AbstractRequest* ThreadPool::PopRequest( REQUEST_QUEUE& RequestQueue_io )
{
AutoLock LockThread( m_LockWorkerThread );
/* if( !RequestQueue_io.empty())
{
AbstractRequest* pRequest = RequestQueue_io.front();
RequestQueue_io.remove( pRequest );
return pRequest;
}*/
return 0;
}
做为c++良好的例子,和学习c++编程思想简单例子