Docs/Standard library

threads

Start native threads from functions, await completion, park and wake threads, and terminate individual threads.

Native threads and IDs#

threads runs first-class Ocean functions and closures on native OS threads. It does not introduce coroutines or a language scheduler. Main always has ID 0; worker IDs are positive integers allocated monotonically and never reused. Completed IDs remain valid throughout program execution.

All identifier-taking functions panic for unknown IDs, including negative IDs. CurrentID panics if called from an unregistered native thread. The API uses plain values and panics for misuse or creation failure, rather than returning Result values.

Native threads and IDs reference
SignatureBehavior
Spawn(job func()) intStart a function or closure and return its thread ID.
CurrentID() intReturn the caller’s ID; main is 0.
Await(id int)Wait for completion and join the native worker.
IsDone(id int) boolReport completion, including deferred cleanup.
Yield()Park the calling thread until a wake arrives while parked.
Wake(id int)Resume a yielded thread; discard wakes of running or completed threads.
Return()Run defers and exit only the caller, from any function depth.
Kill(id int)Request cancellation of the identified thread.

threads.Spawn, threads.CurrentID, and threads.Await#

Spawn(job func()) int starts a zero-argument function with no result and returns its identifier. Use a closure to supply inputs. An uninitialized function or native creation failure panics. CurrentID() identifies the caller.

Await(id) blocks until the target completes and joins the native worker. Multiple threads may await the same target, and repeated awaits after completion return normally. Awaiting yourself panics. IsDone(id) reports whether the function and its deferred calls have completed; use Await when you need to wait rather than poll. A worker can await ID 0; it completes when main returns or terminates.

Closures capture variables by reference. Protect shared mutation with synchronization and keep borrowed pointers valid until the worker finishes. Passing a closure does not make shared state safe automatically.

Ocean
package main;
import "io";
import "threads";

func worker() {
    io.Println("Worker ID: ", threads.CurrentID()).unwrap();
}

func main() {
    id := threads.Spawn(worker);
    threads.Await(id);
    io.Println("Done: ", threads.IsDone(id)).unwrap();
}

threads.Yield and threads.Wake#

Yield() parks the calling OS thread until Wake(id) finds it yielded. It is a blocking park, rather than a request to let the OS briefly run another thread. Main can yield and be woken using ID 0.

A wake only affects a thread that is currently yielded. Waking a running or completed thread does nothing and stores no wake token. In particular, calling Wake immediately after Spawn can arrive too early. Wake of an invalid identifier panics. The runtime makes publishing the yielded state and entering the wait atomic with respect to Wake.

The example retries wakes until the worker completes, so an early wake cannot leave it parked forever. This deliberately demonstrates the lossy wake contract; use synchronization to coordinate more complex work.

Ocean
package main;
import "threads";

func main() {
    id := threads.Spawn(func() { threads.Yield(); });
    for (; !threads.IsDone(id);) {
        threads.Wake(id);
    }
    threads.Await(id);
}

threads.Return#

Return() exits only the calling thread, even from a deeply nested helper. It runs that thread’s deferred calls before marking it complete. It does not return to its caller and is not a panic: recover() returns null during this cleanup and cannot prevent the termination.

Return in main completes ID 0 while allowing workers to continue. To terminate every thread immediately, use os.Exit(code) instead.

Ocean
package main;
import "threads";
import "sync";

func finishHere(done *sync.WaitGroup) {
    defer done.Done();
    threads.Return();
}

func main() {
    done: sync.WaitGroup;
    done.Add(1);
    id := threads.Spawn(func() { finishHere(&done); });
    done.Wait();
    threads.Await(id);
}

threads.Kill and cancellation#

Kill(id) requests cooperative cancellation and returns without waiting for the target to stop. Follow it with Await(id) when completion is required. Killing a completed thread does nothing; killing an unknown ID panics. Killing yourself behaves like Return, and killing ID 0 stops main while letting other workers continue.

Compiler checkpoints cover function entries, loop iterations, and goto jumps. Yield, Await, mutex waits, and wait-group waits also check cancellation. Cancellation runs deferred calls and cannot be recovered as a panic. An unrecovered ordinary panic reports its diagnostic and terminates the whole process.

Arbitrary blocking native calls and long inline assembly are not forcibly interrupted: cancellation waits until execution reaches a checkpoint. Deferred cleanup is not interrupted by cancellation. Register deferred Unlock and Done calls immediately after acquiring ownership or starting a task, so termination does not strand locks or unfinished work.

Ocean
package main;
import "threads";

func main() {
    id := threads.Spawn(func() {
        for (;;) {
            // CPU work remains cancellable at loop checkpoints.
        }
    });
    threads.Kill(id);
    threads.Await(id);
}

Main and process shutdown#

Normal return from main marks ID 0 complete, then waits for workers before freeing closure storage and globals. Wake yielded workers before returning from main; otherwise shutdown can remain blocked. Return or Kill of main stops that one thread while workers continue.

os.Exit(code) immediately terminates the entire process and all threads without deferred calls or process cleanup. It also skips buffered stream cleanup. Await workers before leaving scopes containing borrowed pointers, regardless of which shutdown path the program uses. Existing mutable library registries, such as shared file state, still require caller synchronization.

Platforms and linking#

The native runtime uses pthreads on Linux and macOS and Win32 threads and synchronization on Windows. Importing threads or sync for the WebAssembly target fails compilation with an unsupported-threading diagnostic. Use these packages with the matching updated compiler.

The compiler provides the native entry-point bridge and makes closure allocation safe across threads. Closure capture does not synchronize shared mutable values, and ordinary Ocean function values still cannot be passed directly to native C callbacks. Native runtime code is included only when needed and is stored in the cached program support object. POSIX links add -pthread only for programs requiring native threading or synchronization, including cache hits. Windows uses Win32 APIs and does not link pthread. The compiler embeds runtime_threads.c at build time and compiles it with Clang into program support when needed. Full cache hits only relink. When manually linking saved LLVM for a threaded program, compile and link runtime_threads.c too and add -pthread on POSIX.

The regression suite runs native Linux tests and exercises Windows runtime control flow through a POSIX Win32 API shim. Real Windows and macOS hosts are still required to validate those OS ABIs.