分类:
2008-10-13 16:31:12
信号量的用法和互斥的用法很相似,不同的是它可以同一时刻允许多个线程访问同一个资源
/////////////////////////////////////////////////////H/////////////////////////////////////////////////////////////
#ifndef LGLIB_SEMAPHORE_H
#define LGLIB_SEMAPHORE_H
class __LGLIB__ lg_Semaphore
{
private: // 数据
HANDLE m_semHandle;
lg_AtomicCounter m_nCount;
public: // 构造
/*!
* 可以指定信号量的初始值。这个初始值通常用于指定锁定有限个资源或者指定
* 线程实例可以访问的指定资源的最大值。
*/
lg_Semaphore( uint32 resource = 0 );
/*!
* 析够函数
*/
~lg_Semaphore();
public: // 方法
/*!
* 等待资源可用。
*
* @param timeout 等待超时值。默认为0,表示永远不超时。
* @return 当指定超时值是,TRUE资源可用,FALSE资源不可用,超时;
* 当没有指定超时值时,TRUE资源可用,FALSE发生错误。
*/
bool wait( timeout_t timeout = 0 );
/*!
* 增加可用资源,获释放可用资源给其他线程。
*/
void release( void );
/*!
* 获得当前可用资源数量。
*
* @return 可用资源数量
*/
int32 getValue( void );
};
#endif
//////////////////////////////////////////////CPP/////////////////////////////////////////////////////////
//---------------------------------------------------------------------------
// 构造函数
lg_Semaphore::lg_Semaphore( uint32 resource )
{
m_semHandle = ::CreateSemaphore( ( LPSECURITY_ATTRIBUTES )NULL,
( uint32 )resource, MAX_SEM_VALUE,
( LPCTSTR )NULL );
}
//---------------------------------------------------------------------------
// 析够函数
lg_Semaphore::~lg_Semaphore()
{
::CloseHandle( m_semHandle );
}
//---------------------------------------------------------------------------
// 等待信号
bool lg_Semaphore::wait( timeout_t timeout )
{
if ( m_nCount )
{
--m_nCount;
}
if( !timeout )
{
timeout = INFINITE;
}
return WaitForSingleObject( m_semHandle, timeout) == WAIT_OBJECT_0;
}
//---------------------------------------------------------------------------
// 递增可用资源数量
void lg_Semaphore::release( void )
{
++m_nCount;
::ReleaseSemaphore( m_semHandle, 1, ( LPLONG )NULL );
}
//---------------------------------------------------------------------------
// 获得当前可用资源数量
int32 lg_Semaphore::getValue( void )
{
return m_nCount;
}
posted on 2006-04-29 22:35 longest 阅读(520)