blob: 3ed8a498e8779d8a078ea5aef83a5e84f8f0c96a (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
|
/*
* 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 <bu/readwritemutex.h>
#include <bu/thread.h>
#include <bu/randomcmwc.h>
#include <bu/sio.h>
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;
}
|