00001 #ifndef __J2K__RWLock_HPP__
00002 #define __J2K__RWLock_HPP__
00003
00004 #include <j2k/Fred/Standard.hpp>
00005 #include <j2k/445/Posix/Mutex.hpp>
00006
00007 class RWLock {
00008 public:
00009 inline RWLock()
00010 : readers( 0 ), readfail( 0 ), writefail( 0 ), loop( 0 ) { }
00011
00012 inline virtual ~RWLock() { }
00013
00014 void read() {
00015 readfail = 1;
00016 do {
00017 if ( loop ) sched_yield();
00018 loop = 1;
00019 mutex.lock();
00020 if ( readers >= 0 ) {
00021 readers++;
00022 readfail = 0;
00023 }
00024 mutex.unlock();
00025 } while( readfail );
00026 }
00027
00028 void releaseRead() {
00029 mutex.lock();
00030 if ( readers >= 0 ) {
00031 readers--;
00032 }
00033 mutex.unlock();
00034 }
00035
00036 void releaseWrite() {
00037 mutex.lock();
00038 if ( readers < 0 ) {
00039 readers = 0;
00040 }
00041 mutex.unlock();
00042 }
00043
00044 void write() {
00045 writefail = 1;
00046 do {
00047 if ( loop ) sched_yield();
00048 loop = 1;
00049 mutex.lock();
00050 if ( readers == 0 ) {
00051 readers = -1;
00052 writefail = 0;
00053 }
00054 mutex.unlock();
00055 } while( writefail );
00056 }
00057
00058 private:
00059
00060
00061
00062 long readers;
00063 int readfail;
00064 int writefail;
00065 int loop;
00066 Mutex mutex;
00067 };
00068
00069 #endif