Skip to content

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:

  • Parallel runs 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.
  • Channel carries values from one goroutine to another and blocks the side that is ahead. A select waits on several channels, a context, a wait group, or a timer at once.
  • Context bounds 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 and Cond.wait.
  • The sync types guard memory that goroutines share: Mutex, RwMutex, Atomic, Once, Cond, and WaitGroup, 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:

ant
let words = ["ant", "bee", "wasp"]
let lengths = Parallel.map(words, func(word: string, _: Context) { word.length() }, limit: 2) ?? []
println(lengths.sum())
text
10

For 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:

ant
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)
}
text
ANT
BEE
WASP

A 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:

ant
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())
text
30

A bounded wait ​

A context with a timeout ends the wait. A receive that gives up returns null, and reason says why:

ant
let replies: Channel[string] = Channel.new()
let ctx = Context.new(20ms)
println(replies.receive(ctx: ctx) ?? "no reply")
println(ctx.reason())
text
no reply
timeout

The first of several things ​

A select takes whichever head can proceed first. Its heads are written in namespace form:

ant
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)
text
timed out

For 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:

ant
let winner = Parallel.race([
  {
    Time.sleep(200ms, ctx: x)
    "slow"
  },
  { "fast" },
])
println(winner ?? "cancelled")
text
fast

Parallel.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:

ant
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"])
text
3

A 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 limit at once, results in input order
  • Parallel.each: call a function on every element of an array, or every value of a channel, at most limit at once
  • Os.cpus: the number of CPUs the program may use at once, the limit for CPU-bound work

Taking the first result ​

  • Parallel.race: the first value any function returns, Err included
  • Parallel.any: the first Ok, or Err of 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 capacity values; 0 is a rendezvous
  • Channel.send: send a value, waiting until it is taken or buffered
  • Channel.receive: the next value, or null once 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 ​

Waiting for goroutines to finish ​

Guarding shared data ​

Changing one value without a lock ​

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 ​

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 ​