Try it in the playground

Tasks and threads

task { ... } creates a cooperative coroutine; await drives it to completion and obtains its result. It does not imply another processor is running it. thread { ... } starts an operating-system thread; awaiting it joins the thread and obtains its result. Both require a hosted target.

The example shares no mutable state. To share state between threads, use Shared, Mutex and Weak according to the ownership rules; an ordinary mutable object cannot simply be captured and changed by several threads. Printing after each await gives this program a deterministic output order.

See tasks and threads for cancellation, capture rules and synchronization, and ownership for shared handles.

Runnable source:

import "abla/io"

fun main {
    val cooperative = task { 20 + 22 }
    println("task ${await cooperative}")
    val worker = thread { 6 * 7 }
    println("thread ${await worker}")
}
// output:
// task 42
// thread 42

Previous · Tour · Next

Built from compiler source ba5d6b7d. Examples and generated signatures follow that source revision.