par_map: parallel map without data races
par_map(f, xs) returns exactly what [f(x) for x in xs] would, on every engine. The interpreter and VM run it in order. A native build runs it on several threads when that cannot be observed:
fis a named function (no captures) that is pure scalar code: every local and the result are Int/Float/Bool, and the body only does arithmetic,if/while, calls to other such functions andabs/min/max/sqrt/float/int. Such code allocates nothing and shares no state, so there is nothing to race on. The compiler emits the verdict astrine_fn_pure.xsis an Int or Float list of at least 2048 elements (chunks of ≥1024 per thread).- step counting (
--max-steps) is off, so step counts stay exactly the same as a sequential run.
Errors stay deterministic: if any worker hits a runtime error (division by zero, overflow, depth), all results are discarded and the map is rerun in order, so the error reported is the first failing element's, as in the sequential engines.
TRINE_THREADS=N caps the number of threads (default: online CPUs, at most 64).
Any other function (30). Closures, strings, records, lists: when neither f (its captures) nor xs reaches a capability, f can only compute and print (authority travels only in capability objects), so native code splits the list into one chunk per core and runs each chunk as a task (below). The list and f are marked shared first (atomic counts); everything a chunk creates keeps plain counts and moves to the caller with the chunk's results. Output comes in list order and the error is the first failing element's, as for tasks. With a capability anywhere in f or xs, with --max-steps/--max-output, or with TRINE_THREADS=1, it runs in order.
Scoped tasks: spawn and wait (28b), async/await (20d)
let a = spawn(fn() => simulate(params, 1)) # runs alongside the rest of the function
let b = spawn(fn() => simulate(params, 2))
print(wait(a) + wait(b)) # the results
The meaning is sequential. A program with tasks behaves exactly as if each task ran to completion at its spawn. The output is the same and in the same order (a task's prints appear where it was spawned), and the error is the same. If a task fails, nothing the program did after that spawn is visible. The interpreter and the VM do exactly that. Native code runs each task on its own thread and keeps the same meaning:
- Output goes into segments in program order: the task's, then the spawner's continuation. They are written out as they complete. Without tasks, output goes straight to stdout.
- Errors: when a task or the program fails, every task is waited for, the output is written up to the first error in program order, and that error is reported.
- Effects: before anything touches the outside world (a capability builtin, Python, unchecked C), the tasks spawned so far must have finished successfully.
- Memory: everything a task captures is marked shared before the task starts. Shared objects count references atomically (
rc <= -2encodes the count, so ordinary objects keep the one-compare fast path) and are never treated as unique, so nobody updates them in place. Each thread has its own allocator free lists. Results move to the waiting thread when it joins. - Scope: an unwaited task is joined when its value is dropped, at the latest when the function returns.
Checked rules keep this sound (the isolation checker, 29, below). A Task can't be passed to or returned from a function, stored inside another value except a list, or captured by a lambda.
async fn and await (20d)
async fn fetch(n: Net, url: Str) -> Result[Str, Str]:
let (_, _, body) = http(n, "GET", url, {}, "")? # ordinary, blocking code
Ok(body)
fn main(sys):
let n = net(sys)
let tasks = [fetch(n, u) for u in args(sys)] # every call starts a task
for t in tasks:
print(await t) # results in program order
Calling an async function starts it as a task and gives a Task[T]; await t is wait(t). Nothing else is different: async functions aren't "coloured" (their bodies are ordinary code and they can call anything), and the call fetch(n, u) is exactly spawn(fn() => fetch(n', u')) with the arguments evaluated first, so the arguments follow the isolation rules below. examples/tools/fetch_all.tr fetches its URLs this way: five 300 ms pages take ~0.35 s natively (1.5 s on the interpreter, which runs each task where it starts), and the output is identical, run after run, with any TRINE_TASK_DELAY_US.
Isolation: data races don't compile (29)
Trine has no shared mutable memory: values are immutable to everyone who can see them (an in-place update happens only when a value is unique, and shared values are never unique). The only mutable things are in the outside world, reached through capabilities, so the checker decides which capabilities a task may hold:
| a task's lambda (or an async call's arguments) may capture | because |
|---|---|
| data (numbers, strings, lists, maps, records, ...) | immutable; shared values count atomically |
a Net (net(sys)) | each request is independent; nothing is shared between them |
a Conn or a Lines, or a value holding one: it moves into the task | it has state (a read position): one task owns it |
~~a Sys, a Dir, a Py~~ | tasks could race on files, processes or a Python interpreter |
| ~~a function value~~ | it may hold any of the above |
| ~~a task~~ | tasks stay in the function that started them |
After a value moves into a task, using it again is an error, and a task started in a loop can't take one bound outside the loop (every iteration's task would share it):
task_conn_twice.tr:9:22: type error: `conn` moved into the task started at line 8: a connection
or line reader belongs to one task at a time (open another, or do this inside the task)
Each task's own operations on a Net, Conn or Lines don't wait for other tasks (the main program's capability operations still wait for the tasks it started, as before). So network I/O in tasks overlaps, and the output and the error stay exactly the sequential ones. What can differ is only the order a server sees requests in.
With --max-steps or --max-output, or TRINE_THREADS=1, tasks run where they are spawned; the counts are exact. TRINE_TASK_DELAY_US delays task starts, so tests can check that order never depends on timing. The fuzzer sets it, and a ThreadSanitizer build (TRINE_TSAN=1) of examples/tasks.tr runs clean.
Two fib(36) computations: 155 ms on one thread, 78 ms with a task.