Several things at once

Doing several things at once

wait(list, f) calls the function f for every element of a list, all at the same time, and gives back a list of their results, in the list’s order. The program waits at that line until they are all done.

fn slow(n: int): str {
    wait(0.1) // a pause of 0.1 seconds
    return "item ${n}"
}

items: [str] = wait([1, 2, 3, 4, 5], slow)
print(items)

Output:

["item 1", "item 2", "item 3", "item 4", "item 5"]

The five calls pause at the same time, so this takes about 0.1 seconds, not 0.5.

This is for work that waits: on a server’s answer, on a database, on a pause. For example, the ten top stories of Hacker News:

lock API: str = "https://hacker-news.firebaseio.com/v0"

obj Story {
    id: int = 0
    title: str = ""
    url: str = ""
}

fn story(id: int): Story {
    s: Story = convert(http("${API}/item/${id}.json").get().json())
    return s
}

ids: [int] = convert(http("${API}/topstories.json").get().json())
stories: [Story] = wait(ids.part(0, 10), story)
stories.walk(s) {
    print(s.title)
}

While one call waits for its answer, the others send their requests and read theirs: the ten take about as long as one.

The function

The function takes one element of the list and gives back a result. Its types must fit: for a [int], a fn(int): Story; the result is then a [Story]. It is an ordinary function, written with fn, and given by its name.

How many at once

wait makes at most 16 calls at once: servers don’t like hundreds of connections from one program. The third argument changes it:

fn double(n: int): int {
    return n * 2
}

print(wait([1, 2, 3, 4], double, 2)) // at most 2 at a time

Output:

[2, 4, 6, 8]

With 1, the calls are made one after another, in the list’s order.

Errors

When a call raises an error, wait makes no new calls; the ones that run end, and then the error is raised at the wait line. If several raised one, it is the first in the list’s order.

fn check(n: int): int {
    if n == 3 {
        throw error(103, "no threes")
    }
    return n
}

e: error = nil
try e {
    print(wait([1, 2, 3, 4], check))
}
print(e)

Output:

error 103: no threes

Background work: spawn

spawn(f, ...) starts a function beside the program, and the program goes on at once: the function, then its arguments. It is for work whose result isn’t waited for at one line: sending a message after a server has answered, a cleanup every minute beside a server, a download while the program does something else.

obj Board {
    lines: [str] = []
}

fn note(b: Board, text: str, pause: float) {
    wait(pause)
    b.lines[] = text
}

b: Board = Board {}
spawn(note, b, "slow", 0.03)
spawn(note, b, "fast", 0.01)
print("spawned: ${len(b.lines)} lines yet")
wait()
print(b.lines)

Output:

spawned: 0 lines yet
["fast", "slow"]
  • The function gives nothing back: what it makes goes into an object or list it is given, as b above. To call a function for many elements and gather what each gives, use wait(list, f).
  • wait() waits until what this code spawned has ended: in a function, what that function spawned. So two server handlers that wait for their own work never wait for each other’s.
  • The program waits for all spawned work before it ends: nothing is cut off.
  • An error the function doesn’t catch ends the program, as anywhere else. Work that should go on after an error catches it with try inside the function.
  • A function that loops for ever (while true { wait(60) ... }) runs as long as the program; so the program never ends by itself, as a server doesn’t.

A pause

wait(seconds) pauses the program for that many seconds, an int or a float: wait(2), wait(0.5). A pause in a call that wait(list, f) makes, or in a web server’s handler, lets the others go on meanwhile.

wait(0) doesn’t pause: it lets the others that can run have a turn first, then goes on (alone, it just goes on). Calls that only compute, or write files, never wait, so each runs to its end before the next starts; with a wait(0) in their loop they take turns:

obj Log {
    lines: [str] = []
}

fn writer(l: Log, name: str) {
    (1..3).walk(i) {
        l.lines[] = "${name}${i}"
        wait(0) // the others' turn
    }
}

l: Log = Log {}
spawn(writer, l, "a")
spawn(writer, l, "b")
wait()
print(len(l.lines))

Output:

6

The lines alternate between a and b; which of them starts may differ between luma run and a compiled program. A time below 0 is the same as 0.

Details

  • Only one call’s code runs at any moment: they take turns while they wait (on the network, or a pause). So wait makes waiting faster, not computing: calls that only compute take as long as one after another. The calls can read and change the same objects and lists without locks; but something can change while a call waits, so read it again after.
  • A call can nest 2,000 calls of its own (the main program 10,000).
  • wait works anywhere: in the main program, in functions, in a call wait makes, and in a web server’s handlers.