diff options
Diffstat (limited to '')
-rw-r--r-- | src/tests/readwritemutex.cpp | 106 |
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 | |||
6 | using namespace Bu; | ||
7 | |||
8 | ReadWriteMutex mRW; | ||
9 | bool bRunning; | ||
10 | |||
11 | class Writer : public Thread | ||
12 | { | ||
13 | public: | ||
14 | Writer( int iId ) : | ||
15 | iId( iId ), | ||
16 | rand( iId ) | ||
17 | { | ||
18 | } | ||
19 | |||
20 | virtual ~Writer() | ||
21 | { | ||
22 | } | ||
23 | |||
24 | protected: | ||
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 | |||
38 | private: | ||
39 | int iId; | ||
40 | RandomCmwc rand; | ||
41 | }; | ||
42 | |||
43 | class Reader : public Thread | ||
44 | { | ||
45 | public: | ||
46 | Reader( int iId ) : | ||
47 | iId( iId ), | ||
48 | rand( -iId ) | ||
49 | { | ||
50 | } | ||
51 | |||
52 | virtual ~Reader() | ||
53 | { | ||
54 | } | ||
55 | |||
56 | protected: | ||
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 | |||
70 | private: | ||
71 | int iId; | ||
72 | RandomCmwc rand; | ||
73 | }; | ||
74 | |||
75 | #define CNT 5 | ||
76 | |||
77 | int 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 | |||