summaryrefslogtreecommitdiff
path: root/src/tests
diff options
context:
space:
mode:
authorMike Buland <eichlan@xagasoft.com>2013-02-21 03:55:56 +0000
committerMike Buland <eichlan@xagasoft.com>2013-02-21 03:55:56 +0000
commit9dd51c94844bc7e5f8b1552511d31ed2c9bac05c (patch)
tree3dd505ddea45f47f2a413eba05074a9605afbe6c /src/tests
parent123434f227a963cf26f9637136bf759a824f930a (diff)
downloadlibbu++-9dd51c94844bc7e5f8b1552511d31ed2c9bac05c.tar.gz
libbu++-9dd51c94844bc7e5f8b1552511d31ed2c9bac05c.tar.bz2
libbu++-9dd51c94844bc7e5f8b1552511d31ed2c9bac05c.tar.xz
libbu++-9dd51c94844bc7e5f8b1552511d31ed2c9bac05c.zip
Added the Bu::ReadWriteMutex, which is super awesome. Also made the
Bu::RandomBase::rand functions visible in the Bu::RandomCmwc class.
Diffstat (limited to '')
-rw-r--r--src/tests/readwritemutex.cpp106
1 files changed, 106 insertions, 0 deletions
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 @@
1#include <bu/readwritemutex.h>
2#include <bu/thread.h>
3#include <bu/randomcmwc.h>
4#include <bu/sio.h>
5
6using namespace Bu;
7
8ReadWriteMutex mRW;
9bool bRunning;
10
11class Writer : public Thread
12{
13public:
14 Writer( int iId ) :
15 iId( iId ),
16 rand( iId )
17 {
18 }
19
20 virtual ~Writer()
21 {
22 }
23
24protected:
25 virtual void run()
26 {
27 while( bRunning )
28 {
29 mRW.lockWrite();
30 println("Writer %1 locking.").arg( iId );
31 usleep( rand.rand(5,10)*100000 );
32 println("Writer %1 unlocking.").arg( iId );
33 mRW.unlockWrite();
34 usleep( rand.rand(5,10)*10000 );
35 }
36 }
37
38private:
39 int iId;
40 RandomCmwc rand;
41};
42
43class Reader : public Thread
44{
45public:
46 Reader( int iId ) :
47 iId( iId ),
48 rand( -iId )
49 {
50 }
51
52 virtual ~Reader()
53 {
54 }
55
56protected:
57 virtual void run()
58 {
59 while( bRunning )
60 {
61 mRW.lockRead();
62 println("Reader %1 locking.").arg( iId );
63 usleep( rand.rand(5,10)*100000 );
64 println("Reader %1 unlocking.").arg( iId );
65 mRW.unlockRead();
66 usleep( rand.rand(5,10)*10000 );
67 }
68 }
69
70private:
71 int iId;
72 RandomCmwc rand;
73};
74
75#define CNT 5
76
77int main()
78{
79 bRunning = true;
80
81 Thread **threads = new Thread*[CNT*2];
82 for( int j = 0; j < CNT; j++ )
83 {
84 threads[j] = new Reader( j+1 );
85 threads[j+CNT] = new Writer( j+1 );
86 }
87
88 println("Starting.");
89 for( int j = 0; j < CNT*2; j++ )
90 threads[j]->start();
91
92 sleep( 10 );
93 bRunning = false;
94
95 for( int j = 0; j < CNT*2; j++ )
96 {
97 threads[j]->join();
98 delete threads[j];
99 }
100
101 delete[] threads;
102
103 return 0;
104}
105
106