00001 #ifndef _sys_Semaphore_h
00002 #define _sys_Semaphore_h
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022 #include "Monitor.h"
00023
00024 namespace qpid {
00025 namespace sys {
00026
00027 class Semaphore
00028 {
00029 public:
00030 Semaphore(uint c = 1) : count(c) {}
00031
00032 void lock() { acquire(); }
00033 void unlock() { release(); }
00034 bool trylock() { return tryAcquire(); }
00035
00036 bool tryAcquire()
00037 {
00038 Monitor::ScopedLock l(monitor);
00039 if (count) {
00040 count--;
00041 return true;
00042 } else {
00043 return false;
00044 }
00045 }
00046
00047 void acquire()
00048 {
00049 Monitor::ScopedLock l(monitor);
00050 while (count == 0) monitor.wait();
00051 count--;
00052 }
00053
00054 void release()
00055 {
00056 Monitor::ScopedLock l(monitor);
00057 if (!count++) monitor.notifyAll();
00058 }
00059
00060 private:
00061 Monitor monitor;
00062 uint count;
00063 };
00064
00065 }}
00066
00067 #endif