龙仪的家

导航

<2008年12月>
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910

随笔分类

文章分类

收藏夹

随笔档案

文章档案

统计

我的常用网址

代码库之六-信号量

 信号量的用法和互斥的用法很相似,不同的是它可以同一时刻允许多个线程访问同一个资源

/////////////////////////////////////////////////////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 阅读(551) 评论(0)  编辑 收藏

评论

标题  
姓名  
主页
验证码 *
内容   
  登录  使用高级评论  Top
[使用Ctrl+Enter键可以直接提交]