ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change
on this file since 05c34c3 was
bd12159,
checked in by Peter A. Buhr <pabuhr@…>, 5 years ago
|
complete draft for second version of concurrency paper
|
-
Property mode set to
100644
|
File size:
1.6 KB
|
Line | |
---|
1 | #include <fstream.hfa> |
---|
2 | #include <thread.hfa> |
---|
3 | |
---|
4 | volatile int SharedRW = 0; // shared variable to test readers and writers |
---|
5 | |
---|
6 | monitor ReadersWriter { |
---|
7 | int rcnt, wcnt; // number of readers/writer using resource |
---|
8 | }; |
---|
9 | void EndRead( ReadersWriter & mutex rw ) with(rw) { rcnt -= 1; } |
---|
10 | void EndWrite( ReadersWriter & mutex rw ) with(rw) { wcnt = 0; } |
---|
11 | void StartRead( ReadersWriter & mutex rw ) with(rw) { |
---|
12 | if ( wcnt > 0 ) waitfor( EndWrite, rw ); |
---|
13 | rcnt += 1; |
---|
14 | } |
---|
15 | void StartWrite( ReadersWriter & mutex rw ) with(rw) { |
---|
16 | if ( wcnt > 0 ) waitfor( EndWrite, rw ); |
---|
17 | else while ( rcnt > 0 ) waitfor( EndRead, rw ); |
---|
18 | wcnt = 1; |
---|
19 | } |
---|
20 | void ?{}( ReadersWriter & rw ) with(rw) { rcnt = wcnt = 0; } |
---|
21 | int readers( ReadersWriter & rw ) { return rw.rcnt; } |
---|
22 | void Read( ReadersWriter & rw ) { |
---|
23 | StartRead( rw ); |
---|
24 | sout | "Reader:" | active_thread() | ", shared:" | SharedRW | " with:" | readers( rw ) | " readers"; |
---|
25 | yield( 3 ); |
---|
26 | EndRead( rw ); |
---|
27 | } |
---|
28 | void Write( ReadersWriter & rw ) { |
---|
29 | StartWrite( rw ); |
---|
30 | |
---|
31 | SharedRW += 1; |
---|
32 | sout | "Writer:" | active_thread() | ", wrote:" | SharedRW; |
---|
33 | yield( 1 ); |
---|
34 | EndWrite( rw ); |
---|
35 | } |
---|
36 | thread Worker { |
---|
37 | ReadersWriter &rw; |
---|
38 | }; |
---|
39 | void ?{}( Worker & w, ReadersWriter * rw ) { &w.rw = rw; } |
---|
40 | void main( Worker & w ) with(w) { |
---|
41 | for ( 10 ) { |
---|
42 | if ( rand() % 100 < 70 ) { // decide to be a reader or writer |
---|
43 | Read( rw ); |
---|
44 | } else { |
---|
45 | Write( rw ); |
---|
46 | } // if |
---|
47 | } // for |
---|
48 | } |
---|
49 | int main() { |
---|
50 | enum { MaxTask = 5 }; |
---|
51 | ReadersWriter rw; |
---|
52 | Worker *workers[MaxTask]; |
---|
53 | |
---|
54 | for ( i; MaxTask ) workers[i] = new( &rw ); |
---|
55 | for ( i; MaxTask ) delete( workers[i] ); |
---|
56 | sout | "successful completion"; |
---|
57 | } // main |
---|
58 | |
---|
59 | |
---|
60 | // Local Variables: // |
---|
61 | // tab-width: 4 // |
---|
62 | // compile-command: "cfa -O2 RWMonitor.cfa" // |
---|
63 | // End: // |
---|
Note: See
TracBrowser
for help on using the repository browser.