From 823ebfd6cbdf7d2d4513b784826a9845a8ed670c Mon Sep 17 00:00:00 2001 From: Luis <42945842+ldiaz94@users.noreply.github.com> Date: Mon, 26 Oct 2026 11:39:05 +0000 Subject: [PATCH] Library: Task(T), a thread given a value with no cast; Guarded(T), a value with its lock Task.spawn copies x to the heap; the thread runs p on its copy and frees it. Guarded.with runs p on the value under a Thread.Mutex. Tested in test/run (a generic module has no main of its own); the Guarded test fails without the lock. Breaks no program. --- diff --git a/Makefile b/Makefile index f0553ef..07d26a4 100644 --- a/Makefile +++ b/Makefile @@ -98,7 +98,7 @@ # its sources, in the order of doc/raz-lib.md, between the page's own # head (with its date) and tail LIBDOC = Rt Mem Heap Arena Lock Thread.linux-x86_64 Out Sys.linux-x86_64 \ - Str Bytes.x86_64 Buf Fmt List Map Vec Sort Math Files Opt Width Rand Check Prop C + Str Bytes.x86_64 Buf Fmt List Map Vec Task Guarded Sort Math Files Opt Width Rand Check Prop C man: build/raz-lib.3 diff --git a/README.md b/README.md index ca76fd4..fc66d3d 100644 --- a/README.md +++ b/README.md @@ -211,7 +211,7 @@ (buffered output), `C`, `Lock`, `Thread` (threads, with C or without), `Mem`, `Heap`, `Arena`, `Str`, `Bytes`, `Buf`, `Fmt`, `Math`, `Files`, `Opt` (a command line read through one table), `Width` (the columns of a terminal text takes), `List(T)`, `Map(K, V; hash, eq)`, -`Vec(T)` (a growable array) and `Sort(T; less)`. Volume 2 of the report, `doc/raz-lib.md`, gives each one's interface, +`Vec(T)` (a growable array), `Task(T)` and `Guarded(T)` (threads that take a value, and a value with its lock) and `Sort(T; less)`. Volume 2 of the report, `doc/raz-lib.md`, gives each one's interface, and `tools/Doc.raz` prints it from the module's file: $ ./raz -o Doc tools/Doc.raz && ./Doc lib/Str.raz diff --git a/doc/raz-lib.md b/doc/raz-lib.md index b960624..bebc0ab 100644 --- a/doc/raz-lib.md +++ b/doc/raz-lib.md @@ -21,6 +21,8 @@ | `C` | the parts of the C library the others use, and `printf`, `fflush`, `stdout`, `pthread_create`; a program that imports it uses C | | `Lock` | a lock for short sections, for C's threads and `Thread`'s alike | | `Thread` | threads, `spawn`, `join` and `signal`, and `Mutex`, in any program; in one that uses C, made by C's `pthread_create` | +| `Task` | a thread given a value of its own, `Task(T)`: `spawn` copies it, with no cast | +| `Guarded` | a value with its lock, `Guarded(T)`: reached only through `with` | | `Mem` | `Allocator`, the interface of every allocator, and pages from the system | | `Heap` | a general allocator, `Heap.heap`, safe to call from several threads; freeing a block twice, or one it never gave out, stops the program | | `Arena` | an allocator that frees everything at once; `ADR(arena.base)` is its allocator | @@ -120,7 +122,29 @@ proc signal*(t: ^Thread; sig: INT): INT; (* sig sent to t alone: 0, or minus an errno *) proc lock*(var m: Mutex); proc unlock*(var m: Mutex); + +module Task(T); +proc spawn*(p: proc(var x: T); x: T): (^Thread.Thread, ERROR); (* p run on a copy of x in a new thread *) + +module Guarded(T); +type Guarded* = record ... end; (* a value and its Thread.Mutex; zero is ready *) +proc with*(var g: Guarded; p: proc(var x: T)); (* p run on the value, under the lock *) ``` + +`Task(T)` starts a thread without a cast: `import Jobs := Task(Job); +t, e := Jobs.spawn(work, job);` is the safe form of +`Thread.spawn(work, ^U8(ADR(job)))`. `spawn` copies `x` into a block +from `Heap` before it returns, so the caller may change or drop its `x` +at once. The thread owns the copy: `work` changes it freely, and the +thread frees it when `work` returns. The thread is joined with +`Thread.join`; `Thread.Failed` comes back if there is no memory for the +copy or the thread. A result goes back through a pointer in `x`, read +after `join`. + +`Guarded(T)` is a `T` with its `Thread.Mutex`, for sharing a container +between threads: the value is reached only through `with`, which holds +the lock while `p` runs. A zeroed `Guarded` is ready. `p` must not call +`with` on the same `Guarded`, nor keep a pointer into its `x`. A `Lock` is for short sections: a thread that finds it taken tries again, giving up the processor now and then. A `Mutex` sleeps. Each of diff --git a/doc/raz.md b/doc/raz.md index fdbfa73..a2a9e0d 100644 --- a/doc/raz.md +++ b/doc/raz.md @@ -329,9 +329,9 @@ **Names are flat.** The names of a program's modules are one space, with no packages or paths. So the names of the library's modules (the library, `doc/raz-lib.md`) are kept for it: a program or another library doesn't -name a module of its own `Arena`, `Buf`, `C`, `Files`, `Fmt`, `Heap`, -`List`, `Lock`, `Map`, `Math`, `Mem`, `Opt`, `Out`, `Rt`, `Sort`, -`Str`, `Sys` or `Thread`, nor any name the library takes later. The +name a module of its own `Arena`, `Buf`, `C`, `Files`, `Fmt`, `Guarded`, +`Heap`, `List`, `Lock`, `Map`, `Math`, `Mem`, `Opt`, `Out`, `Rt`, +`Sort`, `Str`, `Sys`, `Task` or `Thread`, nor any name the library takes later. The modules of any other library share a prefix of their own, as an X11 library's `Xauth` and `Xkeys` do, and a program that wants a shorter name imports one: `import Auth := Xauth;`. diff --git a/lib/Guarded.raz b/lib/Guarded.raz new file mode 100644 index 0000000..8626494 --- /dev/null +++ b/lib/Guarded.raz @@ -0,0 +1,33 @@ +(* A value of type T together with the lock that guards it, so that + sharing a container between threads is hard to do wrong: the value + can be reached only through with, which holds the lock while it + runs. + + A Guarded is ready as it is, with a zero value and the lock free; + with can set any other. The lock is a Thread.Mutex, which sleeps + while it waits, so p may take its time. p must not call with on the + same Guarded, which would wait for itself, and must not keep a + pointer into x past its return. + + It depends on Thread. It leaves out reading the value without the + lock, a try-lock and a lock shared by several values: a program + that wants those uses Thread.Mutex itself. *) +module Guarded(T); +import Thread; + +type + Guarded* = record + lock: Thread.Mutex; (* held while the value is used *) + value: T; (* what the lock guards *) + end; + +(* Runs p on the value, holding the lock, so that no other thread uses + it at the same time. *) +proc with*(var g: Guarded; p: proc(var x: T)); +begin + Thread.lock(g.lock); + p(g.value); + Thread.unlock(g.lock); +end; + +end Guarded. diff --git a/lib/Task.raz b/lib/Task.raz new file mode 100644 index 0000000..ee0ba89 --- /dev/null +++ b/lib/Task.raz @@ -0,0 +1,53 @@ +(* A thread that is given a value of type T, with no cast: the safe form + of Thread.spawn, which takes a pointer to bytes. + + spawn copies x into a block from the heap before it returns, so the + caller may change x, or let it go out of scope, at once. The thread + runs p on that copy and frees it when p returns, so the thread owns + its copy from first to last and nobody else has to know when it is + done with it. p can change its copy; the caller never sees it. What + p and x share with others, a pointer in x for one, is the program's + to guard: Guarded is for that. + + It depends on Thread and Heap. It leaves out a way to give p a + result: a thread that returns something writes it through a pointer + in x, and the caller reads it after Thread.join. *) +module Task(T); +import Heap, Mem, Thread; + +type + (* What the thread is given: what to run and its copy of x. *) + Job = record + p: proc(var x: T); + x: T; + end; + +(* Where the new thread starts: runs the job's procedure on its copy, + then frees the copy. *) +proc run(arg: ^U8); +var j: ^Job; +begin + j := ^Job(arg); + j^.p(j^.x); + Mem.free(Heap.heap, arg); +end; + +(* Starts p(x) in a new thread, on a copy of x; join the thread as + Thread.spawn's. Thread.Failed if there is no memory for the copy + or for the thread. *) +proc spawn*(p: proc(var x: T); x: T): (^Thread.Thread, ERROR); +var j: ^Job; t: ^Thread.Thread; err: ERROR; +begin + NEW(j, Heap.heap); + if j = nil then return nil, Thread.Failed; end; + j^.p := p; + j^.x := x; + t, err := Thread.spawn(run, ^U8(j)); + if err # nil then + Mem.free(Heap.heap, ^U8(j)); + return nil, err; + end; + return t, nil; +end; + +end Task. diff --git a/test/run/GuardedTest.expect b/test/run/GuardedTest.expect new file mode 100644 index 0000000..e69de29 diff --git a/test/run/GuardedTest.raz b/test/run/GuardedTest.raz new file mode 100644 index 0000000..881c78c --- /dev/null +++ b/test/run/GuardedTest.raz @@ -0,0 +1,40 @@ +(* Guarded: several threads each add to one counter many times; the total + is exact. *) +module GuardedTest; +import Check, Counter := Guarded(INT), Rt, Thread; + +const + Threads = 8; + Times = 20000; + +var count: Counter.Guarded; + +proc add(var x: INT); +begin + INC(x); +end; + +proc check(var x: INT); +begin + Check.int("Guarded: total", x, Threads * Times); +end; + +(* One thread's share of the work. *) +proc work(_arg: ^U8); +var i: INT; +begin + for i := 1 to Times do Counter.with(count, add); end; +end; + +proc main*; +var t: [Threads]^Thread.Thread; i: INT; err: ERROR; +begin + for i := 0 to Threads - 1 do + t[i], err := Thread.spawn(work, nil); + if err # nil then Rt.stop("Thread.spawn failed"); end; + end; + for i := 0 to Threads - 1 do Thread.join(t[i]); end; + Counter.with(count, check); +end; + +end GuardedTest. diff --git a/test/run/TaskTest.expect b/test/run/TaskTest.expect new file mode 100644 index 0000000..e69de29 diff --git a/test/run/TaskTest.raz b/test/run/TaskTest.raz new file mode 100644 index 0000000..0c387e6 --- /dev/null +++ b/test/run/TaskTest.raz @@ -0,0 +1,36 @@ +(* Task: each of several threads is given its own job; the caller changes + its job at once after spawn, and the threads' copies are not changed. *) +module TaskTest; +import Check, Jobs := Task(Job), Rt, Thread; + +const Threads = 8; + +(* A thread's job: a number, and where to put its square. *) +type Job = record n: INT; out: ^INT; end; + +var results: [Threads]INT; + +(* Puts n squared where the job says, then changes its own copy. *) +proc work(var j: Job); +begin + j.out^ := j.n * j.n; + j.n := 0; +end; + +proc main*; +var t: [Threads]^Thread.Thread; j: Job; i: INT; err: ERROR; +begin + for i := 0 to Threads - 1 do + j := {n: i + 1, out: ADR(results[i])}; + t[i], err := Jobs.spawn(work, j); + if err # nil then Rt.stop("Task.spawn failed"); end; + j.n := 1000; (* the thread must not see this *) + j.out := ADR(results[0]); + end; + for i := 0 to Threads - 1 do Thread.join(t[i]); end; + for i := 0 to Threads - 1 do + Check.int("Task: result", results[i], (i + 1) * (i + 1)); + end; +end; + +end TaskTest.