raz / lib / Task.raz

54 lines · 1.6 KiB · raw · history · last change e0d008cd

1(* A thread that is given a value of type T, with no cast: the safe form
2 of Thread.spawn, which takes a pointer to bytes.
3
4 spawn copies x into a block from the heap before it returns, so the
5 caller may change x, or let it go out of scope, at once. The thread
6 runs p on that copy and frees it when p returns, so the thread owns
7 its copy from first to last and nobody else has to know when it is
8 done with it. p can change its copy; the caller never sees it. What
9 p and x share with others, a pointer in x for one, is the program's
10 to guard: Guarded is for that.
11
12 It depends on Thread and Heap. It leaves out a way to give p a
13 result: a thread that returns something writes it through a pointer
14 in x, and the caller reads it after Thread.join. *)
15module Task(T);
16import Heap, Mem, Thread;
17import SYSTEM;
18
19type
20 (* What the thread is given: what to run and its copy of x. *)
21 Job = record
22 p: proc(var x: T);
23 x: T;
24 end;
25
26(* Where the new thread starts: runs the job's procedure on its copy,
27 then frees the copy. *)
28proc run(arg: ^U8);
29var j: ^Job;
30begin
31 j := ^Job(arg);
32 j^.p(j^.x);
33 Mem.free(Heap.heap, arg);
34end;
35
36(* Starts p(x) in a new thread, on a copy of x; join the thread as
37 Thread.spawn's. Thread.Failed if there is no memory for the copy
38 or for the thread. *)
39proc spawn*(p: proc(var x: T); x: T): (^Thread.Thread, ERROR);
40var j: ^Job; t: ^Thread.Thread; err: ERROR;
41begin
42 NEW(j, Heap.heap);
43 if j = nil then return nil, Thread.Failed; end;
44 j^.p := p;
45 j^.x := x;
46 t, err := Thread.spawn(run, ^U8(j));
47 if err # nil then
48 Mem.free(Heap.heap, ^U8(j));
49 return nil, err;
50 end;
51 return t, nil;
52end;
53
54end Task.