Language guide · 10 of 12

Concurrency: go, await, & Task

Evie provides built-in cooperative concurrency inspired by Go goroutines and JavaScript async/await.

Spawning Tasks (go)

Use the go keyword followed by a function call to run it concurrently:

task := go fetchRemoteData()

// Or invoke an inline anonymous function:
inline := go fn() {
    return fetchRemoteData()
}()
Open in playground

Awaiting Tasks (await)

await pauses the current fiber until the task completes and unwraps the result:

data := await task
Open in playground

Multi-Task Concurrency (await.all, await.any, await.race, await.timeout)

t1 := go fetchServiceA()
t2 := go fetchServiceB()

// Wait for all to succeed (returns array of results)
results := await.all(t1, t2)
// Or pass an array:
results = await.all([t1, t2])

// Wait for first successful task (ignores failures unless all fail)
firstSuccess := await.any(t1, t2)

// Wait for first task to settle (whether success or error)
winner := await.race(t1, t2)

// Wait for a task with a deadline in milliseconds (cancels and throws on timeout)
bounded := await.timeout(t1, 500)
Open in playground

Task Methods

t.done()       // returns boolean: whether the task has settled
t.isDone()     // alias for t.done()
t.result()     // returns task result (or nil)
t.error()      // returns error (or nil)
t.await()      // method form of await
t.cancel()     // requests cooperative cancellation of the task
Open in playground

Shared State

Only one fiber of an instance executes Evie code at a time. The rule for when it hands over is short: a fiber yields only when it waits. That happens in exactly three places:

Nothing else hands over: arithmetic, assignments, method calls, go itself, io.println, json, math. A call to one of your own functions yields only if it reaches one of the three places, as a helper that calls time.wait does. Between those points a fiber runs uninterrupted, so shared variables, arrays, objects and classes never need locks:

var counter := 0

fn worker(n) {
    while n > 0 {
        counter += 1 // never lost: no other fiber runs until this one awaits
        n -= 1
    }
}

fn main() {
    await.all(go worker(500), go worker(500))
    return counter // always 1000
}
Open in playground

Edit this page on GitHub