| 1 | (* Guarded: several threads each add to one counter many times; the total |
| 2 | is exact. *) |
| 3 | module GuardedTest; |
| 4 | import Check, Counter := Guarded(INT), Rt, Thread; |
| 5 | |
| 6 | const |
| 7 | Threads = 8; |
| 8 | Times = 20000; |
| 9 | |
| 10 | var count: Counter.Guarded; |
| 11 | |
| 12 | proc add(var x: INT); |
| 13 | begin |
| 14 | INC(x); |
| 15 | end; |
| 16 | |
| 17 | proc check(var x: INT); |
| 18 | begin |
| 19 | Check.int("Guarded: total", x, Threads * Times); |
| 20 | end; |
| 21 | |
| 22 | (* One thread's share of the work. *) |
| 23 | proc work(_arg: ^U8); |
| 24 | var i: INT; |
| 25 | begin |
| 26 | for i := 1 to Times do Counter.with(count, add); end; |
| 27 | end; |
| 28 | |
| 29 | proc main*; |
| 30 | var t: [Threads]^Thread.Thread; i: INT; err: ERROR; |
| 31 | begin |
| 32 | for i := 0 to Threads - 1 do |
| 33 | t[i], err := Thread.spawn(work, nil); |
| 34 | if err # nil then Rt.stop("Thread.spawn failed"); end; |
| 35 | end; |
| 36 | for i := 0 to Threads - 1 do Thread.join(t[i]); end; |
| 37 | Counter.with(count, check); |
| 38 | end; |
| 39 | |
| 40 | end GuardedTest. |