| 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. *) |
| 3 | module TaskTest; |
| 4 | import Check, Jobs := Task(Job), Rt, Thread; |
| 5 | import SYSTEM; |
| 6 | |
| 7 | const Threads = 8; |
| 8 | |
| 9 | (* A thread's job: a number, and where to put its square. *) |
| 10 | type Job = record n: INT; out: ^INT; end; |
| 11 | |
| 12 | var results: [Threads]INT; |
| 13 | |
| 14 | (* Puts n squared where the job says, then changes its own copy. *) |
| 15 | proc work(var j: Job); |
| 16 | begin |
| 17 | j.out^ := j.n * j.n; |
| 18 | j.n := 0; |
| 19 | end; |
| 20 | |
| 21 | proc main*; |
| 22 | var t: [Threads]^Thread.Thread; j: Job; i: INT; err: ERROR; |
| 23 | begin |
| 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; |
| 35 | end; |
| 36 | |
| 37 | end TaskTest. |