blob: 980a4a34fb44f9e630baba497c0a17800e8a83d1 (
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
|
#include <bu/thread.h>
#include <bu/synchroqueue.h>
#include <bu/list.h>
class Thing
{
public:
Thing( int x ) :
x( x ),
y( 0 )
{
}
int x;
int y;
};
typedef Bu::SynchroQueue<Thing *> ThingQueue;
Bu::Mutex mWorkDone;
int iWorkDone;
Bu::Condition cWorkDone;
void workDone()
{
mWorkDone.lock();
iWorkDone--;
if( iWorkDone == 0 )
{
mWorkDone.unlock();
cWorkDone.lock();
cWorkDone.signal();
cWorkDone.unlock();
return;
}
mWorkDone.unlock();
}
class ThingEater : public Bu::Thread
{
public:
ThingEater( ThingQueue &qThing ) :
qThing( qThing )
{
}
bool bRunning;
void setRunning( bool b )
{
mRunning.lock();
bRunning = b;
mRunning.unlock();
}
bool isRunning()
{
mRunning.lock();
bool b = bRunning;
mRunning.unlock();
return b;
}
protected:
virtual void run()
{
setRunning( true );
while( isRunning() )
{
Thing *pThing = qThing.dequeue( 0, 250000 );
if( pThing == NULL )
continue;
pThing->y = pThing->x*2;
usleep( 10000 );
workDone();
}
}
ThingQueue &qThing;
Bu::Mutex mRunning;
};
typedef Bu::List<ThingEater *> ThingEaterList;
int main()
{
ThingQueue qThing;
ThingEaterList lEater;
mWorkDone.lock();
iWorkDone = 1000;
mWorkDone.unlock();
for( int j = 0; j < 5; j++ )
lEater.append( new ThingEater( qThing ) );
for( ThingEaterList::iterator i = lEater.begin(); i; i++ )
(*i)->start();
for( int j = 0; j < 1000; j++ )
{
qThing.enqueue( new Thing( j ) );
}
mWorkDone.lock();
mWorkDone.unlock();
cWorkDone.lock();
for(;;)
{
mWorkDone.lock();
if( iWorkDone == 0 )
{
mWorkDone.unlock();
break;
}
mWorkDone.unlock();
cWorkDone.wait();
}
cWorkDone.unlock();
for( ThingEaterList::iterator i = lEater.begin(); i; i++ )
(*i)->setRunning( false );
for( ThingEaterList::iterator i = lEater.begin(); i; i++ )
(*i)->join();
return 0;
}
|