| 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. *) |
| 15 | module Task(T); |
| 16 | import Heap, Mem, Thread; |
| 17 | import SYSTEM; |
| 18 | |
| 19 | type |
| 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. *) |
| 28 | proc run(arg: ^U8); |
| 29 | var j: ^Job; |
| 30 | begin |
| 31 | j := ^Job(arg); |
| 32 | j^.p(j^.x); |
| 33 | Mem.free(Heap.heap, arg); |
| 34 | end; |
| 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. *) |
| 39 | proc spawn*(p: proc(var x: T); x: T): (^Thread.Thread, ERROR); |
| 40 | var j: ^Job; t: ^Thread.Thread; err: ERROR; |
| 41 | begin |
| 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; |
| 52 | end; |
| 53 | |
| 54 | end Task. |