Grav v1.14.0

Async, Mutex, AtomicInt and Channel

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

Tools for async code: control over the worker pool, and the three basic ways to share data safely between tasks. The Concurrency chapter explains when to use each.

ClassFor
Asyncthe worker pool: setMaxProcs, maxProcs, pending, cpuCount, sleepMs
Mutexletting one thread at a time run a piece of code: withLock(body)
AtomicInta counter many threads update without a lock
Channel<T>passing values from producers to consumers
awaitAll(futures)awaiting an Array<Future<T>>, giving an Array<T>
grav
import "std"

async fn worker(id: int, jobs: Channel<int>, done: AtomicInt, log: Mutex, lines: Array<string>) {
    while (jobs.hasNext()) {
        let n = jobs.receiveOr(-1)
        if (n < 0) { continue }
        done.increment()
        log.withLock(fn() { lines.push("${n * n}") })
    }
}

fn main() {
    let jobs = new Channel<int>(4)
    let done = new AtomicInt(0)
    let log = new Mutex()
    let lines = new Array<string>()
    let workers = new Array<Future<void>>()
    for (id in 0..3) { workers.push(worker(id, jobs, done, log, lines)) }
    for (n in 1..=10) { jobs.send(n) }
    jobs.close()
    for (w in workers) { await w }
    print(done.get())
    print(lines.size())
}
Output
10
10
  • Mutex.withLock(body) releases the lock even if body throws. lock(), unlock() and tryLock() are there for finer control.
  • AtomicInt has get, set, add, increment, decrement (which return the new value) and compareAndSet(expected, desired).
  • Channel<T>(capacity): send waits while the channel is full; receive waits while it is empty and throws StateError once it is closed and drained; receiveOr(fallback) returns the fallback then; hasNext() waits until there is a value (true) or the channel is closed and empty (false). Sending to a closed channel returns false.
  • Async.setMaxProcs(n) sets the size of the worker pool (also GRAV_MAXPROCS).

API

class Async

Worker-pool settings and thread info.

Static members

  • static fn maxProcs() -> int — How many worker threads async calls may use.
  • static fn setMaxProcs(n: int) — Change the limit (takes effect for workers started from now on).
  • static fn pending() -> int — Tasks spawned but not finished yet.
  • static fn cpuCount() -> int — The number of CPU cores online.
  • static fn threadId() -> long — An identifier for the calling thread (differs between workers).
  • static fn sleepMs(ms: int) — Pauses the calling thread for ms milliseconds.

class Mutex

A mutual-exclusion lock. Prefer withLock, which unlocks even on exceptions.

Constructors

  • new Mutex()

Methods

  • fn lock() — Takes the lock, waiting while another thread holds it.
  • fn unlock() — Releases the lock.
  • fn tryLock() -> bool — Takes the lock if it is free right now; whether it did.
  • fn withLock(body: fn()) — Runs body holding the lock (released even when body throws).

class AtomicInt

A 64-bit integer updated atomically (no lock needed).

Constructors

  • new AtomicInt(initial: long)

Methods

  • fn get() -> long — The current value.
  • fn set(n: long) — Sets the value.
  • fn add(n: long) -> long — Adds and returns the new value.
  • fn increment() -> long — Adds 1 and returns the new value.
  • fn decrement() -> long — Subtracts 1 and returns the new value.
  • fn compareAndSet(expected: long, desired: long) -> bool — Sets to desired only if the value is expected; reports success.

class AtomicLong

A 64-bit counter or value updated atomically (the same as AtomicInt, which is 64-bit too; the name says so). updateMax keeps the largest value seen.

Constructors

  • new AtomicLong(initial: long = 0)

Methods

  • fn get() -> long
  • fn set(n: long)
  • fn add(n: long) -> long — Adds and returns the new value.
  • fn increment() -> long
  • fn decrement() -> long
  • fn exchange(n: long) -> long — Sets a new value and returns the old one.
  • fn compareAndSet(expected: long, desired: long) -> bool
  • fn updateMax(n: long) -> long — Raises the value to n if n is larger (a running maximum); the value after.

class AtomicBool

A flag set and read atomically across threads (a stop request, say).

Constructors

  • new AtomicBool(initial: bool = false)

Methods

  • fn get() -> bool
  • fn set(b: bool)
  • fn getAndSet(b: bool) -> bool — Sets it and returns what it was (true: someone set it first).
  • fn compareAndSet(expected: bool, desired: bool) -> bool

class Channel<T>

A bounded, blocking, thread-safe queue for handing values between tasks. send() waits while full; receive() waits while empty. After close(), sends fail and receivers drain what is left; hasNext() reports whether more will come.

Constructors

  • new Channel(capacity: int)

Methods

  • fn send(v: T) -> bool — Blocks while the channel is full. Returns false if it has been closed.
  • fn hasNext() -> bool — Blocks until a value is available or the channel is closed and empty.
  • fn receiveOr(fallback: T) -> T — Takes the next value, or returns fallback once closed and drained.
  • fn receive() -> T — Takes the next value; StateError once the channel is closed and empty.
  • fn close() — No more sends; wakes every waiting sender and receiver.
  • fn size() -> int — The number of values waiting in the channel.

Functions

  • fn awaitAll<T>(futures: Array<Future<T>>) -> Array<T> — Waits for every future, in order, and collects the results.

Edit this page on GitHub