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.
| Class | For |
|---|---|
Async | the worker pool: setMaxProcs, maxProcs, pending, cpuCount, sleepMs |
Mutex | letting one thread at a time run a piece of code: withLock(body) |
AtomicInt | a 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> |
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())
}10
10Mutex.withLock(body)releases the lock even ifbodythrows.lock(),unlock()andtryLock()are there for finer control.AtomicInthasget,set,add,increment,decrement(which return the new value) andcompareAndSet(expected, desired).Channel<T>(capacity):sendwaits while the channel is full;receivewaits while it is empty and throwsStateErroronce 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 returnsfalse.Async.setMaxProcs(n)sets the size of the worker pool (alsoGRAV_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 formsmilliseconds.
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())— Runsbodyholding 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 todesiredonly if the value isexpected; 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() -> longfn set(n: long)fn add(n: long) -> long— Adds and returns the new value.fn increment() -> longfn decrement() -> longfn exchange(n: long) -> long— Sets a new value and returns the old one.fn compareAndSet(expected: long, desired: long) -> boolfn updateMax(n: long) -> long— Raises the value tonifnis 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() -> boolfn 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 returnsfallbackonce 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.