From 9dd51c94844bc7e5f8b1552511d31ed2c9bac05c Mon Sep 17 00:00:00 2001 From: Mike Buland Date: Thu, 21 Feb 2013 03:55:56 +0000 Subject: Added the Bu::ReadWriteMutex, which is super awesome. Also made the Bu::RandomBase::rand functions visible in the Bu::RandomCmwc class. --- src/tests/readwritemutex.cpp | 106 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 src/tests/readwritemutex.cpp (limited to 'src/tests') diff --git a/src/tests/readwritemutex.cpp b/src/tests/readwritemutex.cpp new file mode 100644 index 0000000..d00956d --- /dev/null +++ b/src/tests/readwritemutex.cpp @@ -0,0 +1,106 @@ +#include +#include +#include +#include + +using namespace Bu; + +ReadWriteMutex mRW; +bool bRunning; + +class Writer : public Thread +{ +public: + Writer( int iId ) : + iId( iId ), + rand( iId ) + { + } + + virtual ~Writer() + { + } + +protected: + virtual void run() + { + while( bRunning ) + { + mRW.lockWrite(); + println("Writer %1 locking.").arg( iId ); + usleep( rand.rand(5,10)*100000 ); + println("Writer %1 unlocking.").arg( iId ); + mRW.unlockWrite(); + usleep( rand.rand(5,10)*10000 ); + } + } + +private: + int iId; + RandomCmwc rand; +}; + +class Reader : public Thread +{ +public: + Reader( int iId ) : + iId( iId ), + rand( -iId ) + { + } + + virtual ~Reader() + { + } + +protected: + virtual void run() + { + while( bRunning ) + { + mRW.lockRead(); + println("Reader %1 locking.").arg( iId ); + usleep( rand.rand(5,10)*100000 ); + println("Reader %1 unlocking.").arg( iId ); + mRW.unlockRead(); + usleep( rand.rand(5,10)*10000 ); + } + } + +private: + int iId; + RandomCmwc rand; +}; + +#define CNT 5 + +int main() +{ + bRunning = true; + + Thread **threads = new Thread*[CNT*2]; + for( int j = 0; j < CNT; j++ ) + { + threads[j] = new Reader( j+1 ); + threads[j+CNT] = new Writer( j+1 ); + } + + println("Starting."); + for( int j = 0; j < CNT*2; j++ ) + threads[j]->start(); + + sleep( 10 ); + bRunning = false; + + for( int j = 0; j < CNT*2; j++ ) + { + threads[j]->join(); + delete threads[j]; + } + + delete[] threads; + + return 0; +} + + -- cgit v1.2.3