raz / test / run / TaskTest.raz

37 lines · 1.0 KiB · raw · history · last change 264716cb

1(* Task: each of several threads is given its own job; the caller changes
2 its job at once after spawn, and the threads' copies are not changed. *)
3module TaskTest;
4import Check, Jobs := Task(Job), Rt, Thread;
5import SYSTEM;
6
7const Threads = 8;
8
9(* A thread's job: a number, and where to put its square. *)
10type Job = record n: INT; out: ^INT; end;
11
12var results: [Threads]INT;
13
14(* Puts n squared where the job says, then changes its own copy. *)
15proc work(var j: Job);
16begin
17 j.out^ := j.n * j.n;
18 j.n := 0;
19end;
20
21proc main*;
22var t: [Threads]^Thread.Thread; j: Job; i: INT; err: ERROR;
23begin
24 for i := 0 to Threads - 1 do
25 j := {n: i + 1, out: SYSTEM.ADR(results[i])};
26 t[i], err := Jobs.spawn(work, j);
27 if err # nil then Rt.stop("Task.spawn failed"); end;
28 j.n := 1000; (* the thread must not see this *)
29 j.out := SYSTEM.ADR(results[0]);
30 end;
31 for i := 0 to Threads - 1 do Thread.join(t[i]); end;
32 for i := 0 to Threads - 1 do
33 Check.int("Task: result", results[i], (i + 1) * (i + 1));
34 end;
35end;
36
37end TaskTest.