raz / test / run / GuardedTest.raz

40 lines · 844 B · raw · history · last change 823ebfd6

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