00001 /* 00002 wefts_semaphore.h 00003 Semaphore object header file. 00004 00005 $Id: wefts_semaphore.h,v 1.5 2004/03/28 21:45:40 jonnymind Exp $ 00006 --------------------------------------- 00007 Begin : Mon, 08 Mar 2004 21:52:32 +0100 00008 Author : Giancarlo Niccolai 00009 00010 Last modified because: 00011 Implementing OS independent base threading 00012 */ 00013 00014 /************************************************************************** 00015 * This program is free software; you can redistribute it and/or modify * 00016 * it under the terms of the GNU Library General Public License as * 00017 * published by the Free Software Foundation; either version 2.1 of the * 00018 * License, or (at your option) any later version. * 00019 ***************************************************************************/ 00020 00021 #ifndef WT_SEMAPHORE_H 00022 #define WT_SEMAPHORE_H 00023 00024 #include <wefts_fastcond.h> 00025 00026 namespace Wefts { 00027 00048 class Semaphore: public CleanupHandler 00049 { 00050 private: 00051 int m_count; 00052 int m_waiting; 00053 FastCondition m_cond; 00054 00055 public: 00071 Semaphore( int initial_count = 1 ) 00072 { 00073 m_count = initial_count; 00074 m_waiting = 0; 00075 } 00076 00084 inline int value() { return m_count; } 00085 00093 inline int waiters() { return m_waiting; } 00094 00108 inline void post(int amount=1) { 00109 m_cond.lock(); 00110 m_count+=amount; 00111 // todo: would be greatly optimized if signal would not do a broadcast. 00112 if ( m_waiting > 0 ) 00113 { 00114 if ( m_count == 1 ) 00115 m_cond.signalOne(); 00116 else if ( m_count > 1 ) 00117 m_cond.signal(); 00118 } 00119 m_cond.unlock(); 00120 } 00121 00142 void wait(CleanupHandler *handler = 0, int position = 0); 00143 00158 bool wait( double seconds, CleanupHandler *handler = 0, int position = 0 ); 00159 00167 bool tryWait() 00168 { 00169 bool ret; 00170 m_cond.lock(); 00171 if ( m_count > 0 ) { 00172 m_count --; 00173 ret = true; 00174 } 00175 else 00176 ret = false; 00177 m_cond.unlock(); 00178 00179 return ret; 00180 } 00181 00182 virtual void handleCleanup( int code, void *caller=0 ); 00183 }; 00184 00185 } 00186 #endif 00187 /* end of wefts_semaphore.h */