Grav v1.14.0

Thread and synchronisation

import "std/concurrency" (included in import "std") · namespace std.concurrency

A Thread is a dedicated operating-system thread, for long-running or blocking work: a server's accept loop, a background worker, a file watcher. (For short pieces of work, async functions on the shared pool are lighter.) This module also has the classic synchronisation tools.

grav
import "std"

fn main() {
    let total = new AtomicInt(0)
    let wg = new WaitGroup()
    for (i in 0..4) {
        wg.add(1)
        Thread.spawn(fn() {
            for (k in 0..1000) { total.increment() }
            wg.done()
        }).detach()
    }
    wg.wait()
    print("total: ${total.get()}")

    let failing = Thread.spawn("worker", fn() { throw new ValueError("disk full") })
    print("worker: " + failing.joinResult())

    let pool = new Semaphore(2)
    let t = Thread.spawn(fn() { pool.withPermit(fn() { print("inside the semaphore") }) })
    t.join()

    let once = new Once()
    for (i in 0..3) { once.run(fn() { print("initialised once") }) }
}
Output
total: 4000
worker: ValueError: disk full
inside the semaphore
initialised once
TypeFor
Threadspawn(body) or new Thread(body).start(); join() waits (and throws StateError if the body failed); joinResult() returns "" or the failure; detach() lets it run on its own
WaitGroupwaiting for a group of threads: add(n), done(), wait(), waitFor(ms)
CountDownLatcha gate that opens after n calls to countDown()
Semaphoreallowing at most n threads into a section: acquire, release, withPermit(body)
RWLockmany readers or one writer: withRead(body), withWrite(body)
Oncerunning an initialiser exactly once, however many threads call run

An exception or a panic inside a thread ends that thread only; join() reports it. withPanicRecovery(false) before start() makes a panic in that thread stop the whole program instead.

Threads share data through objects, not by assigning captured variables (those are copies). Protect shared mutable objects with a Mutex or RWLock, or use AtomicInt and Channel from async.

API

class Thread

A dedicated OS thread running body. An exception that escapes the body is caught and kept: join() reports it.

Constructors

  • new Thread(body: fn())
  • new Thread(name: string, body: fn())

Static members

  • static fn spawn(body: fn()) -> Thread — Create and start a thread in one step.
  • static fn spawn(name: string, body: fn()) -> Thread — Creates a thread named name running body and starts it.
  • static fn sleepMs(ms: int) — Pauses the calling thread for ms milliseconds.
  • static fn yieldNow() — Give other threads a chance to run.
  • static fn currentId() -> long — An id for the calling thread.
  • static fn cpuCount() -> int — The number of CPU cores online.

Methods

  • fn withPanicRecovery(on: bool) -> Thread — Before start(): this thread's own panic-recovery setting (by default it follows Panic.setRecovery).
  • fn start() — Starts running the body (StateError when already started).
  • fn join() — Wait for the thread to finish. Throws StateError if its body threw.
  • fn joinResult() -> string — Like join(), but returns the failure ("" when the body finished normally).
  • fn detach() — Let the thread run on its own; it can no longer be joined.
  • fn getName() -> string — The thread's name.
  • fn isStarted() -> bool — Whether start() was called.

class WaitGroup

Waits for a group of threads or tasks: add(n) before starting each, done() when one finishes, wait() until the count drops to zero.

Constructors

  • new WaitGroup()

Methods

  • fn add(n: int) — Adds n to the count of pending tasks.
  • fn done() — Marks one task as finished (count - 1).
  • fn wait() — Waits until the count reaches zero.
  • fn waitFor(ms: int) -> bool — Wait at most ms milliseconds; reports whether the count reached zero.
  • fn count() -> int — The current count.

class CountDownLatch

A one-shot gate: countDown() n times opens it, and every wait() returns.

Constructors

  • new CountDownLatch(n: int)

Methods

  • fn countDown() — Counts down by one; waiters wake at zero.
  • fn wait() — Waits until the count reaches zero.
  • fn waitFor(ms: int) -> bool — Waits at most ms milliseconds; whether the count reached zero.

class Semaphore

Limits how many threads use a resource at once: acquire() takes a permit (waiting if none are left), release() returns it.

Constructors

  • new Semaphore(permits: int)

Methods

  • fn acquire() — Takes a permit, waiting while there is none.
  • fn tryAcquire() -> bool — Takes a permit if one is free right now; whether it did.
  • fn release() — Gives back a permit.
  • fn withPermit(body: fn()) — Run body holding a permit (released even if it throws).

class RWLock

Many readers or one writer.

Constructors

  • new RWLock()

Methods

  • fn readLock() — Waits for shared (read) access.
  • fn writeLock() — Waits for exclusive (write) access.
  • fn unlock() — Releases the read or write access.
  • fn withRead(body: fn()) — Runs body with read access (released even when body throws).
  • fn withWrite(body: fn()) — Runs body with write access (released even when body throws).

class Once

Runs a function exactly once, however many threads call run().

Constructors

  • new Once()

Methods

  • fn run(body: fn()) — Runs body the first time it is called, from whichever thread gets there first.
  • fn isDone() -> bool — Whether run() has finished its body.

Edit this page on GitHub