source: doc/papers/concurrency/examples/RWMonitorINT.cfa @ d0cd933

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since d0cd933 was 2aab69b, checked in by Peter A. Buhr <pabuhr@…>, 5 years ago

files added to concurrency paper

  • Property mode set to 100644
File size: 1.8 KB
Line 
1#include <fstream.hfa>
2#include <thread.hfa>
3
4volatile int SharedRW = 0;                                                              // shared variable to test readers and writers
5
6enum RW { READER, WRITER };
7monitor ReadersWriter {
8        int rcnt, wcnt;                                                                         // number of readers/writer using resource
9        condition RWers;
10};
11
12void ?{}( ReadersWriter & rw ) with(rw) { rcnt = wcnt = 0; }
13void StartRead( ReadersWriter & mutex rw ) with(rw) {
14        if ( wcnt !=0 || ! is_empty( RWers ) ) wait( RWers, READER );
15        rcnt += 1;
16        if ( ! is_empty( RWers ) && front( RWers ) == READER ) signal( RWers );
17}
18void EndRead( ReadersWriter & mutex rw ) with(rw) {
19        rcnt -= 1;
20        if ( rcnt == 0 ) signal( RWers );
21}
22void StartWrite( ReadersWriter & mutex rw ) with(rw) {
23        if ( wcnt != 0 || rcnt != 0 ) wait( RWers, WRITER );
24        wcnt = 1;
25}
26void EndWrite( ReadersWriter & mutex rw ) with(rw) {
27        wcnt = 0;
28        signal( RWers );
29}
30int readers( ReadersWriter & rw ) { return rw.rcnt; }
31
32void Read( ReadersWriter & rw ) {
33        StartRead( rw );
34        sout | "Reader:" | active_thread() | ", shared:" | SharedRW | " with:" | readers( rw ) | " readers";
35        yield( 3 );
36        EndRead( rw );
37}
38void Write( ReadersWriter & rw ) {
39        StartWrite( rw );
40
41        SharedRW += 1;
42        sout | "Writer:" | active_thread() | ",  wrote:" | SharedRW;
43        yield( 1 );
44        EndWrite( rw );
45}
46
47thread Worker {
48        ReadersWriter &rw;
49};
50void ?{}( Worker & w, ReadersWriter * rw ) { &w.rw = rw; }
51void main( Worker & w ) with(w) {
52        for ( 10 ) {
53                if ( rand() % 100 < 70 ) {                                      // decide to be a reader or writer
54                        Read( rw );
55                } else {
56                        Write( rw );
57                } // if
58        } // for
59}
60
61int main() {
62        enum { MaxTask = 5 };
63        ReadersWriter rw;
64        Worker *workers[MaxTask];
65
66        for ( i; MaxTask ) workers[i] = new( &rw );
67        for ( i; MaxTask ) delete( workers[i] );
68        sout | "successful completion";
69} // main
70
71// Local Variables: //
72// tab-width: 4 //
73// compile-command: "cfa -O2 RWMonitorINT.cfa" //
74// End: //
Note: See TracBrowser for help on using the repository browser.