/* * Copyright (C) 2007-2013 Xagasoft, All rights reserved. * * This file is part of the libbu++ library and is released under the * terms of the license contained in the file LICENSE. */ #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; }