[7bef8cf] | 1 | #include <fstream.hfa> |
---|
| 2 | #include <thread.hfa> |
---|
| 3 | |
---|
| 4 | volatile int SharedRW = 0; // shared variable to test readers and writers |
---|
| 5 | |
---|
| 6 | enum RW { READER, WRITER }; |
---|
| 7 | monitor ReadersWriter { |
---|
| 8 | int rcnt, wcnt; // number of readers/writer using resource |
---|
| 9 | condition RWers; |
---|
| 10 | }; |
---|
| 11 | |
---|
| 12 | void ?{}( ReadersWriter & rw ) with(rw) { rcnt = wcnt = 0; } |
---|
| 13 | void 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 | } |
---|
| 18 | void EndRead( ReadersWriter & mutex rw ) with(rw) { |
---|
| 19 | rcnt -= 1; |
---|
| 20 | if ( rcnt == 0 ) signal( RWers ); |
---|
| 21 | } |
---|
| 22 | void StartWrite( ReadersWriter & mutex rw ) with(rw) { |
---|
| 23 | if ( wcnt != 0 || rcnt != 0 ) wait( RWers, WRITER ); |
---|
| 24 | wcnt = 1; |
---|
| 25 | } |
---|
| 26 | void EndWrite( ReadersWriter & mutex rw ) with(rw) { |
---|
| 27 | wcnt = 0; |
---|
| 28 | signal( RWers ); |
---|
| 29 | } |
---|
| 30 | int readers( ReadersWriter & rw ) { return rw.rcnt; } |
---|
| 31 | |
---|
| 32 | void Read( ReadersWriter & rw ) { |
---|
| 33 | StartRead( rw ); |
---|
| 34 | sout | "Reader:" | active_thread() | ", shared:" | SharedRW | " with:" | readers( rw ) | " readers"; |
---|
| 35 | yield( 3 ); |
---|
| 36 | EndRead( rw ); |
---|
| 37 | } |
---|
| 38 | void 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 | |
---|
| 47 | thread Worker { |
---|
| 48 | ReadersWriter &rw; |
---|
| 49 | }; |
---|
| 50 | void ?{}( Worker & w, ReadersWriter * rw ) { &w.rw = rw; } |
---|
| 51 | void 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 | |
---|
| 61 | int 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: // |
---|