Concurrency
Ant runs concurrent work on goroutines. A go block starts one and returns at once, with no handle to join and no result to read. The program ends when the script ends, without waiting for goroutines still running, so wait for them with a WaitGroup or a channel. A panic in a goroutine ends only that goroutine, and the runtime reports it on standard error. The standard library gives you four kinds of tools to coordinate them:
Parallelruns work whose shape you know when it starts: every element of an array, every job on a channel, or a few different tasks. Each call starts its goroutines, waits for all of them, and raises a callback's panic in the caller.Channelcarries values from one goroutine to another and blocks the side that is ahead. Aselectwaits on several channels, a context, a wait group, or a timer at once.Contextbounds a wait with a deadline or ends it with a cancellation. Every blocking library call takes one as its last parameter,ctx:, except the locks andCond.wait.- The sync types guard memory that goroutines share:
Mutex,RwMutex,Atomic,Once,Cond, andWaitGroup, which waits for goroutines to finish.
Picking a tool
Work over an array
Parallel.map calls a function on every element, at most limit at once, and returns the results in input order. The callback gets a context to pass to its own waits. A lambda takes one parameter, so the callback is a func with two. The result is null when the context ends before every element starts, so give it a fallback:
let words = ["ant", "bee", "wasp"]
let lengths = Parallel.map(words, func(word: string, _: Context) { word.length() }, limit: 2) ?? []
println(lengths.sum())10For CPU-bound work, limit: Os.cpus() runs at most one callback per CPU the program may use at once; see Os.cpus. For I/O-bound work, such as fetching URLs, pick a limit that suits the remote side.
A stream of values
A goroutine sends on a channel and closes it when it is done. A for loop over Channel.values receives until the close:
let names: Channel[string] = Channel.new()
go {
defer { names.close() }
for name in ["ant", "bee", "wasp"] {
names.send(name.toUpper())
}
}
for name in names.values() {
println(name)
}ANT
BEE
WASPA worker pool
A goroutine feeds jobs into a channel and closes it, and Parallel.each hands each job to one of at most limit workers. each stops when the channel closes; it does not close the channel itself:
let jobs: Channel[int] = Channel.new()
go {
defer { jobs.close() }
for n in [1, 2, 3, 4] {
jobs.send(n)
}
}
let total = Atomic.new(0)
Parallel.each(jobs, func(n: int, _: Context) { total.add(n * n) }, limit: 2)
println(total.load())30A bounded wait
A context with a timeout ends the wait. A receive that gives up returns null, and reason says why:
let replies: Channel[string] = Channel.new()
let ctx = Context.new(20ms)
println(replies.receive(ctx: ctx) ?? "no reply")
println(ctx.reason())no reply
timeoutThe first of several things
A select takes whichever head can proceed first. Its heads are written in namespace form:
let replies: Channel[string] = Channel.new()
go {
Time.sleep(200ms)
replies.send("late")
}
let reply = select {
let r = Channel.receive(replies) { r }
Time.sleep(20ms) { "timed out" }
}
println(reply)timed outFor the first of several tasks, use Parallel.race, which cancels the others once one returns. Each task is a lambda whose x is the context to pass to its waits:
let winner = Parallel.race([
{
Time.sleep(200ms, ctx: x)
"slow"
},
{ "fast" },
])
println(winner ?? "cancelled")fastParallel.any works the same way for tasks that return a Result, and gives the first Ok.
Shared data
Goroutines that write the same map take a mutex around each change. A wait group tells the main goroutine when they have all finished, and defer counts a goroutine done even if it panics:
let counts: Map[string, int] = Map{}
let lock = Mutex.new()
let wg = WaitGroup.new()
for word in ["ant", "bee", "ant", "wasp", "ant"] {
wg.add(1)
go {
defer { wg.done() }
lock.withLock({ counts[word] = (counts[word] ?? 0) + 1 })
}
}
wg.wait()
println(counts["ant"])3A goroutine hands back a result through a container, such as an array slot, a map entry, a record field, or an Atomic, not by reassigning a local of its parent.
Functions by job
Starting work
- go: run a block on a new goroutine and return at once
- Parallel.run: call every function at once and wait for all of them
Working through many values
- Parallel.map: apply a function to every element, at most
limitat once, results in input order - Parallel.each: call a function on every element of an array, or every value of a channel, at most
limitat once - Os.cpus: the number of CPUs the program may use at once, the
limitfor CPU-bound work
Taking the first result
- Parallel.race: the first value any function returns,
Errincluded - Parallel.any: the first
Ok, orErrof every error when all fail - select: wait for the first of several channels, contexts, wait groups, or timers
Passing values between goroutines
- Channel.new: an open channel that buffers up to
capacityvalues; 0 is a rendezvous - Channel.send: send a value, waiting until it is taken or buffered
- Channel.receive: the next value, or
nullonce the channel is closed and drained - Channel.values: a sequence of every value until the channel is closed and drained
- Channel.close: close the channel; receivers drain it and then get
null - Channel.isClosed: whether the channel has been closed
- Channel.length: the number of values buffered now
- Time.ticker: a channel that receives the current instant at intervals
Bounding and cancelling waits
- Context.new: a child of a parent or of the run, with an optional timeout
- Context.cancel: make the context done now, with the reason
"cancelled" - Context.isDone: whether the context is done
- Context.reason: why it is done, or
nullwhile it runs - Context.deadline: the earliest deadline of the context and its parents
- Context.wait: wait until the context is done; also a head of
select - Os.interrupt: the context that Ctrl-C, SIGINT, or SIGTERM ends
- Test.context: the context that ends with the current test
- Time.sleep: block for a duration, or until the context is done
Waiting for goroutines to finish
- WaitGroup.new: a new group, its counter at zero
- WaitGroup.add: add
n, which may be negative, to the counter - WaitGroup.done: take one off the counter, as a goroutine finishes
- WaitGroup.wait: block until the counter is zero, or until
ctxis done
Guarding shared data
- Mutex.new: a new, unlocked mutex
- Mutex.withLock: lock, run a function, unlock even if it panics, and return its result
- Mutex.lock: lock, waiting while the mutex is locked
- Mutex.unlock: unlock; panics if the mutex is not locked
- RwMutex.new: a new, unlocked reader-writer lock
- RwMutex.withRead: run a function under the read lock and return its result
- RwMutex.withWrite: run a function under the write lock and return its result
- RwMutex.readLock: lock for reading, waiting while a writer holds the lock or waits for it
- RwMutex.readUnlock: release one read lock
- RwMutex.writeLock: lock for writing, waiting while any reader or writer holds it
- RwMutex.writeUnlock: release the write lock
Changing one value without a lock
- Atomic.new: a new cell holding a value
- Atomic.load: the value in the cell
- Atomic.store: set the value in the cell
- Atomic.add: add to a number and return the new value; panics on overflow
- Atomic.compareAndSwap: set the value only if it equals an expected one
Doing work once
- Once.new: a new once that has not run yet
- Once.do: run a function on the first call only; later calls wait for it and do nothing
- Once.value: a function that runs the loader on its first call and caches its value
Waiting for a condition
- Cond.new: a new cond over a mutex
- Cond.wait: release the mutex, wait for a wake-up, and lock the mutex again
- Cond.signal: wake one waiting goroutine, if any
- Cond.broadcast: wake every waiting goroutine
Containing panics
- Panic.catch: call a function and return its panic as an
Err, so a worker goes on to its next job - Panic.raise: panic again with a caught panic's message and trace
See also
- Concurrency: how goroutines, channels, contexts, and the sync types fit together
- How-to guides: process a list in parallel, run a worker pool, give up after a timeout, take the first result, cancel a group of goroutines, protect shared state, run something periodically
- Time: durations, sleeps, and tickers
