00001 #ifndef SEMAPHORE_IMPLEMENTATION_FILE
00002 #define SEMAPHORE_IMPLEMENTATION_FILE
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018 #include "mechanisms_implementation_only.h"
00019 #include "semaphore.h"
00020
00021 #include <basis/function.h>
00022 #include <basis/istring.h>
00023 #include <basis/mutex.h>
00024 #include <basis/portable.h>
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034 semaphore::semaphore(int concurrent_locks, int initial_locks_available)
00035 : _max_users(0),
00036 _locks_available(0),
00037 _wait_guard(new mutex),
00038 _signal_guard(new mutex),
00039 _current_state(0)
00040 {
00041 if (concurrent_locks < 1) concurrent_locks = 1;
00042 _max_users = concurrent_locks;
00043 if (initial_locks_available < 0) initial_locks_available = 0;
00044 else if (initial_locks_available > concurrent_locks)
00045 initial_locks_available = concurrent_locks;
00046 _locks_available = initial_locks_available;
00047 _current_state = _locks_available;
00048 }
00049
00050 semaphore::~semaphore()
00051 {
00052 delete _wait_guard;
00053 _wait_guard = NIL;
00054 delete _signal_guard;
00055 _signal_guard = NIL;
00056 }
00057
00058 void semaphore::establish_lock() { wait(); }
00059
00060 void semaphore::repeal_lock() { signal(); }
00061
00062 void semaphore::wait()
00063 {
00064 _wait_guard->lock();
00065
00066 while (non_positive(_current_state)) portable::sleep_ms(10);
00067
00068
00069 _current_state--;
00070 _wait_guard->unlock();
00071 }
00072
00073 void semaphore::signal()
00074 {
00075 FUNCDEF("signal");
00076 _signal_guard->lock();
00077 _current_state++;
00078 if (_current_state > _max_users)
00079 LOG("semaphore::signal: logic error! the semaphore is greater than "
00080 "its maximum!");
00081 _signal_guard->unlock();
00082 }
00083
00084
00085 #endif //SEMAPHORE_IMPLEMENTATION_FILE
00086