00001 #ifndef __SYS_SEMWAIT__ 00002 #define __SYS_SEMWAIT__ 00003 00004 /******************************************************************************/ 00005 /* X r d S y s S e m W a i t */ 00006 /* */ 00007 /* Author: Fabrizio Furano (INFN, 2005) */ 00008 /* */ 00009 /* A counting semaphore with timed out wait primitive */ 00010 /******************************************************************************/ 00011 00012 // $Id: XrdSysSemWait.hh 22437 2008-03-04 14:35:16Z rdm $ 00013 00014 #include "XrdSys/XrdSysPthread.hh" 00015 00016 class XrdSysSemWait { 00017 public: 00018 00019 int CondWait() { 00020 00021 int rc = 0; 00022 // Wait until the sempahore value is positive. This will not be starvation 00023 // free is the OS implements an unfair mutex; 00024 // Returns 0 if signalled, non-0 if would block 00025 // 00026 00027 semVar.Lock(); 00028 if (semVal > 0) semVal--; 00029 else { 00030 rc = 1; 00031 } 00032 00033 semVar.UnLock(); 00034 00035 return rc; 00036 00037 }; 00038 00039 void Post() { 00040 // Add one to the semaphore counter. If we the value is > 0 and there is a 00041 // thread waiting for the sempagore, signal it to get the semaphore. 00042 // 00043 semVar.Lock(); 00044 00045 if (semWait > 0) { 00046 semVar.Signal(); 00047 semWait--; 00048 } 00049 else 00050 semVal++; 00051 00052 semVar.UnLock(); 00053 }; 00054 00055 void Wait() { 00056 // Wait until the sempahore value is positive. This will not be starvation 00057 // free is the OS implements an unfair mutex; 00058 // 00059 00060 semVar.Lock(); 00061 if (semVal > 0) semVal--; 00062 else { 00063 semWait++; 00064 semVar.Wait(); 00065 } 00066 00067 semVar.UnLock(); 00068 00069 }; 00070 00071 int Wait(int secs) { 00072 int rc = 0; 00073 // Wait until the sempahore value is positive. This will not be starvation 00074 // free is the OS implements an unfair mutex; 00075 // Returns 0 if signalled, non-0 if timeout 00076 // 00077 00078 semVar.Lock(); 00079 if (semVal > 0) semVal--; 00080 else { 00081 semWait++; 00082 rc = semVar.Wait(secs); 00083 if (rc) semWait--; 00084 } 00085 00086 semVar.UnLock(); 00087 00088 return rc; 00089 }; 00090 00091 XrdSysSemWait(int semval=1,const char *cid=0) : semVar(0, cid) { 00092 semVal = semval; semWait = 0; 00093 } 00094 00095 ~XrdSysSemWait() {} 00096 00097 private: 00098 00099 XrdSysCondVar semVar; 00100 int semVal; 00101 int semWait; 00102 }; 00103 00104 00105 00106 #endif