Joyeer Language Specification
Chapters
On this page (9 sections)

§21 Concurrency: Tasks

Status: tasks and channels are implemented as source-prelude declarations on Windows, Linux, and macOS ARM64 (decisions 0018, 0019, and 0023, on the model in 0013).

21.1 Purpose and model

Joyeer's concurrency is share-nothing. A task is a function running on its own operating system thread. Data crosses from one thread to another only by being moved: into a task as its input, out of a task as its result, and (with channels) as a message. There is no shared mutable state in user code, no lock, no atomic and no fence.

Moving a value never creates an alias (§4.2.3), a borrow cannot be stored or sent (§4.8), and a top-level let is immutable data (§3.1.1), so a program that uses only tasks cannot race on user memory. This guarantee is about memory. It does not cover files, ports, the working directory, child processes, output order or deadlock.

21.2 Starting a task

func square(value: consuming Int): Int { return value * value }

func main() {
    let handle = spawn(function: square, input: 7)            // JoinHandle<Int>
    let answer = consume handle.join()
    print(value: answer)                                      // 49
}

spawn is a generic source-library function in the prelude, not a keyword, declared with the parameters function and input. The ordinary call rules check the labels and their order (name-resolution.argument-out-of-order, argument-count-mismatch). A declaration of the name in the current module, file or lexical scope takes precedence over it; a name imported from another module does not (§12.3).

The call has type JoinHandle<R>, where R is the function's result type (Void included).

21.2.1 The target

The function must be:

(A generic function is also rejected: it is not a function value, §20.4.1.) A public function of a source dependency may be a target; a private one is not visible (§12).

function: still takes a function's name, not an arbitrary function value (§5.6.1). The source signature uses (consuming I): R, but its closed prelude compatibility contract preserves this restriction and the diagnostics above. The internal generic task entry is specialized through the runtime-only callback-address operation (§20.12.5); that does not admit public generic task targets. A function value may itself be a task's input or result and may be sent through a channel.

21.2.2 Ownership

The input is moved into the task when spawn commits. A named value passed with consume is uninitialized afterwards (§4.2.3). A heap value (a String, an array, a Dict) is not cloned; an aggregate's own bytes are copied into the task's storage and the heap parts they reference move with it. Passing consume pair.first follows the ordinary partial-move rules (a type with deinit cannot be partially moved). A top-level constant array (§3.1.1) passed as the input, or returned as the result, is cloned, never freed by the task or the joiner. A JoinHandle may itself be an input or a result. A library array bound by the role array_type (§20.12.5) is a valid input exactly when its element type is; it is bitwise relocatable, and an array of JoinHandle may be passed with consume and ended in the task. A library dictionary bound by dict_type is likewise a valid input or result exactly when its key and value are; it holds no linear key or value.

21.3 Joining

JoinHandle<R> is a linear generic source-library struct (§2.6.3) with a single public member:

consuming func join(): R     // spelled consume handle.join()

join waits for the task to finish and returns the owned result. It is the only way to end a handle, and like any consuming member it must be written consume h.join() on an owned handle (a borrowed or inout handle is invalid-consume-argument). A JoinHandle<R> is linear (§4.1.1, §4.7.1): it must be ended on every path out of the scope that owns it, and it cannot be dropped, copied, or overwritten while live. A program that does not join a task does not compile (semantic-analysis.linear-not-consumed, whose help names join), so there are no detached tasks, and main returns only after every task has finished, which is what lets the allocation-balance check run on a quiescent program (see runtime).

Consequences of the linear rules:

A fan-out over several tasks keeps the handles in an array and drains it with removeLast() (§2.6.2), ending the empty array with consumeEmpty() (§2.6.4):

func total(count: Int): Int {
    var handles: [JoinHandle<Int>] = []
    var index = 0
    while index < count {
        &handles.append(element: consume spawn(function: square, input: consume (index + 1)))
        index = index + 1
    }
    var sum = 0
    while true {
        let popped = &handles.removeLast()
        match consume popped {
            .Some(handle) => { sum = sum + consume handle.join() }
            .None => { break }
        }
    }
    consume handles.consumeEmpty()
    return sum
}

A spawn inside a deinit is allowed; it is join-on-drop and carries that hazard (§21.6).

21.4 Memory-model rules

These happens-before edges are sequentially consistent:

  1. spawn happens before the first statement of the task.
  2. The end of the task, including the destruction of its locals, happens before the join that returns its result.
  3. The input of spawn is visible in the task and the result of join is visible to the joiner, with no further synchronization.

A deinit (§3.7.1) runs on the thread that owns the value when it is destroyed: a moved input's on the task, a joined result's on the joiner. Output from different tasks with no such edge between them has no specified order, but each print call is atomic. Users get no relaxed atomics and no fences.

A trap in any task ends the whole process: output is flushed once, the first trap wins if two occur together, no destructor runs on any task, and resources in flight are released only by the operating system. A task blocked in join is ended with the rest. There is no way to observe a task's failure from join.

21.5 Limits and failure

At most 256 tasks may be unjoined at once, each with an 8 MiB stack; neither is configurable. When the limit is reached, or the operating system refuses a thread, spawn traps with too many tasks or cannot start task; a failing join traps with cannot join task. The trap is deliberate: a recoverable trySpawn that returns the unspent input is a later addition. A stack overflow in a task is not trapped by the language: it ends in the operating system's fault handling (the main thread's stack size differs, 8 MiB on Linux and 1 MiB on Windows).

21.6 Restrictions

21.7 Diagnostics

Type checking unless noted.

IDRejects
spawn-target-not-functionfunction: is not a name that resolves to a function (a variable, an expression)
spawn-target-unsupportedthe target is a method, @c_extern/@c_export or main
spawn-target-parametersthe target does not have exactly one parameter, or it is not consuming
spawn-target-neverthe target returns Never
name-resolution.argument-out-of-order, argument-count-mismatch, unexpected-argument-labelwrong labels, order, or a missing or extra argument of spawn
invalid-consume-argumentinput: on a place without consume; join without consume or on a temporary, borrowed, or inout handle
copy-of-noncopyablecopying a JoinHandle
linear-collection-element, linear-top-level-binding, linear-in-deinit-typea handle in a Dict or for-in, a top-level let, or a deinit type
semantic-analysis.linear-not-consumeda path leaves a handle unjoined
semantic-analysis.linear-overwrite, linear-result-dropped, use-after-consumeoverwriting a live handle; dropping an owned one; using a moved input
semantic-analysis.run-process-with-tasksuse of System's runProcess or startProcess in a program that calls spawn

An unknown function: name is name resolution's ordinary unknown-name diagnostic.

21.8 Grammar

No production is added: spawn(function: f, input: consume x) is an ordinary call (Appendix C, call_arg). The restriction on function: is a type-checking rule, not a grammar rule.

21.9 Channels

Status: implemented in phases P5b and P6 (decision 0019).

A channel carries values from one task to another. It is bounded, has exactly one sender end and one receiver end, and moves each value: a value sent is gone from the sender and owned by whoever receives it. There is still no shared state in user code.

21.9.1 Creating a channel

var sender: ChannelSender<Int>
var receiver: ChannelReceiver<Int>
channel(capacity: 8, sender: &sender, receiver: &receiver)

channel is a generic prelude library function whose last two parameters are initializing (§4.10): each argument is & of an uninitialized (or wholly consumed) mutable local, or of an initializing parameter, so a wrapper function can take two initializing parameters and call channel. The two have types ChannelSender<T> and ChannelReceiver<T> for the same T, and both are initialized by the call. T is any type that is not linear (§4.7.1), Any or Never; Void is allowed as a pure signal, and a nested channel end is allowed (the request/reply idiom). Any remains reserved syntax (§1.4), so it cannot be written as a type argument. The rule applies at every occurrence of the types in a type position. A capacity that is an integer literal below 1 is a compile-time error; any other capacity below 1 traps (invalid channel capacity), and one whose buffer size overflows traps (channel too large).

ChannelSender<T>, ChannelReceiver<T> and the enumeration ChannelClosed (one case, Closed) are source-prelude declarations; a user declaration of the same name takes precedence in its scope (§21.2).

Creating a channel with concrete element type T is rejected if a message of type T can own a prelude ChannelReceiver<T>. Check exact type identity after substituting generic arguments, following stored fields, enum payloads, and elements of the prelude collections. A channel end and a function value are leaves for this check; phantom type arguments do not own anything. This rule applies to creation, not to mentioning an end type. It also rejects carrying a receiver of the same element type from a different channel instance. Use a different reply element type instead.

21.9.2 The ends

Each end is noncopyable (§4.1.1): copying one is type-checking.copy-of-noncopyable. An end is not linear: it is closed when its owner is destroyed, on every path, so a ? or an early return needs no cleanup. An end moves like any noncopyable value, into a task as its input, out as part of its result, into an array or a struct field.

21.9.3 Sending and receiving

match sender.send(value: consume 5) {
    .Ok(_) => (),
    .Err(_) => print(value: "the receiver is gone"),
}
match receiver.receive() {
    .Ok(value) => print(value: value),
    .Err(_) => print(value: "closed"),
}
while true {
    match receiver.receive() {
        .Ok(job) => handle(job: consume job),
        .Err(_) => { break }
    }
}

Matching receiver.receive() directly can transfer a payload into the arm without an additional clone (§7.1.2). The channel still copies the value's own representation bytes into and out of the queue.

Waiting for any receiver

waitForChannel(receivers: [ChannelReceiver<T>]): Int borrows an array of 1 to 64 receivers and returns a zero-based index into that array. An entry is ready if a value is queued or its sender has closed. The wait does not dequeue or reserve a value. Without an intervening receive, a call to receive() on the selected end does not wait for data or closure. A drained closed channel stays ready, so a caller must handle receive() returning .Err(.Closed). The selection does not promise fairness or an atomic snapshot across queues. An invalid count traps, as does a call that would sleep with no unjoined thread.

21.9.4 Closing

consume sender.close() and consume receiver.close() end a handle immediately, like destroying it; the binding is uninitialized afterwards and may be assigned again. An end also closes when its owner is destroyed, including an end held in an array, a struct field or an Optional; to close one element of an array, remove it with removeLast() first (consume a[i].close() is rejected). Closing the sender wakes a blocked receive; closing the receiver wakes a blocked send and destroys every value still queued, on the closing thread after it has taken them out of the channel and released its lock, so the deinit of a channel element may use other channels. The channel's storage is freed by the second end to close, which is decided under the lock. A blocked operation's own end is borrowed for the call, so only the peer can close and wake it.

21.9.5 Memory model and limits

All operations on one channel are totally ordered by the channel's lock (there is no ordering across different channels beyond each thread's program order), so §21.4 holds: a send happens before the receive that gets its value, and closing the sender, after every earlier send, happens before the receiver observes the closed result. A value is moved, not copied; its own bytes are copied into the queue and out of it.

The creation rule prevents a message from storing the receiver for its own queue. Distinct queues can still leak if they hold each other's only receivers. Such a cycle is memory safe and the leak check at exit reports it; the language does not detect it.

A program can deadlock: every thread blocked, a cycle of full channels, or a join of a task waiting on an end the joiner still holds (the sender its loop receives from, or the receiver a blocked producer needs). Close that end (by consuming it) before the join. The language does not detect this, with one exception: a single-threaded program (no unjoined thread) that would wait traps with channel deadlock: nothing can wake this thread. A channel of capacity n holds at most n values.

21.9.6 Diagnostics

IDRejects
type-checking.invalid-initializing-argument, semantic-analysis.initializing-initialized-storagean operand of channel without &, not an uninitialized mutable local or initializing parameter, or already initialized
type-checking.channel-end-typesthe two operands are not a ChannelSender<T> and a ChannelReceiver<T> of the same T
type-checking.channel-capacitya literal capacity below 1
type-checking.linear-channel-elementan element type that is linear
type-checking.channel-receiver-cyclea channel creation whose element could own a receiver for the same element type
lexer.unsupported-syntaxwritten Any, including as a channel type argument
type-checking.channel-element-typean element type of Never
type-checking.copy-of-noncopyablecopying an end
type-checking.invalid-consume-argumentsend without consume on a place value; close without consume, on a borrowed end, or on an array element
semantic-analysis.use-after-consumeusing an end after close