docs

You are reading the docs for v0.1.2. Nabi 0.1.2 is no longer supported. Latest release: v0.1.3 →

#3.4. thread:: - OS threads (1:1 model)

On this page

The std::thread module is the entry point for OS-level threads. As set out in 2.18 task, it is a separate abstraction from tasks, which run on the M:N cooperative scheduler; this module provides the path for spawning native threads directly.

#3.4.1. When to use thread vs. task

The following table indicates which to choose in which situation.

SituationRecommendation
General concurrency / async I/Otask::spawn (lightweight)
CPU-bound computationtask::spawn or par::* (work-stealing)
Blocking C library callsthread::spawn (avoids blocking the task scheduler)
Where an OS thread API is requiredthread::spawn (TLS, signal mask, etc.)
Embedded / no-taskthread::spawn

In short, tasks come first wherever they are light and expressive enough, and dropping down to threads is for places that must deal with OS resources directly.

#3.4.2. API

The basic types and function signatures are as follows.

Thread::unpark sets that thread's park token and wakes it. A token is consumed by one park.

thread::spawn is Builder::spawn with defaults behind try!: where Builder::spawn throws (no threads on the target, or the OS refuses a new thread), thread::spawn panics. Use Builder::new().spawn(f) to handle the error.

await handle (2.20.5) waits for the thread from inside a task: the join runs on the executor's blocking lane (task::spawn_blocking), so only the task waits. It yields T; an OS join failure (JoinError) panics, so call join to handle it.

#Panics and JoinError

A panic in any thread terminates the whole process with exit code 101. join therefore never receives another thread's panic, and thread::panicking() is true only for code that runs on the panicking thread while the process ends (an embedder's exit hook). JoinError represents OS-level join failures (JoinErrorKind::Os), or JoinErrorKind::Lost for a thread that ended with a failed REPL cell (refs-lang 9.7.0), displayed as "thread join failed: the thread ended with a failed REPL cell".

JoinErrorKind::Taken: the handle, or a copy of it, was already joined or detached. A second join throws it; a second detach does nothing.

#3.4.3. Examples

From the simplest spawn-join pattern to builders and multiple spawns:

#3.4.4. Thread-local storage

When each thread needs its own independent storage, use thread::local.

nabi
let counter = thread::local(|| 0);

try thread::spawn(|| {
    counter.set(counter.get() + 1);         // only this thread's value changes
}).join();

The shape follows Rust's LocalKey. with(f) lends the current thread's value to f and returns what f returns. The value is a scoped view, tracked like a lock guard's value (stdlib 2.16.3): returning it out of f, storing it past the call (a capture, a field, a Cell), sending it, or passing it to a callee that keeps it is compile error E0136, and so is giving with an async closure, whose future would hold the value across an await and could resume on another worker thread. Keep a clone(), or what f computes, instead.

nabi
static SEEN: ThreadLocal<List<str>> = thread::local(|| -> List<str> { [] });

SEEN.with(|l| l.push("a"));             // changes this thread's list in place
let n = SEEN.with(|l| l.len());          // what f computes comes out
let copy = SEEN.with(|l| l.clone());     // so does a copy
let all = SEEN.take();                   // the list itself, leaving []

The owned forms move values in and out: set(v) stores v, replace(v) stores v and returns the old value, take() returns the value and leaves T::default(). get() returns a copy and needs T: Copy; for any other T it is a compile error (use with, replace or take). unsafe fn as_ptr() points at the current thread's value; the slot stays pinned until the thread ends, and reads and writes through the pointer are the caller's responsibility.

with takes a closure that cannot await, so a thread's value is never held across an await, where the task may resume on another thread.

#3.4.5. impl / target

Per-platform support:

Itemlinux/macos/windowswasm32-wasip2 / browserwasm32-wasip1-threads
spawn✓panics (Unsupported from Builder::spawn)✓
Builder::spawn✓throws Unsupported✓
local✓✓ (one thread)✓
park/unparkfutex / WaitOnAddress✓✓

On wasm32-wasip2 and in the browser there is one thread: thread::current().name() is none. On wasm32-wasip1-threads, nabi_cpu_count() and the available parallelism are 4, since WASI cannot report a core count.

Found a mistake? Edit this page on GitHub. Last updated