tasks.jamo (built in)

tasks: several jobs at once, taking turns. spawn starts a task, which runs when the one running now lets it: by calling next_turn, wait_seconds, wait_until or wait_all. They all share one processor core, so two tasks never run at the same moment, and nothing needs locks. Good for games, timers, downloads and anything that waits a lot.

use "tasks.jamo"
func count(name: string, times: int)
    for i in 0..times
        print(f"{name} {i}")
        next_turn()
    end
end
func main()
    spawn(func() => count("a", 3))
    spawn(func() => count("b", 3))
    wait_all()
end

A run error in a task that nothing catches stops the whole program, the same as anywhere else. A try only catches errors from its own task. When main ends, the program ends, even if tasks are still going.

Each task is a Windows fiber with its own 8 MB stack, like main's.

constTASKS_MOST

const TASKS_MOST = 10000

constTASKS_STACK

const TASKS_STACK = 8388608

constTASKS_STACK_START

const TASKS_STACK_START = 65536

structTask

struct Task
    work: func()
    fiber: int
    wake: float        # It may run again from this many seconds since the program started
    alive: bool        # Spawned and not finished yet
    waits_for_all: bool  # In wait_all: it may run again once every other task has finished
    finished: bool     # Finished, with its fiber still to be deleted
end

functasks_setup

func tasks_setup()

functasks_nothing

func tasks_nothing()

functasks_entry

func tasks_entry(place: int): int

Where place's rsp and top are kept while it waits

functasks_go

func tasks_go(place: int)

Goes to the task at place, and comes back here when something goes back to this one

functasks_tidy

func tasks_tidy()

Deletes the fibers of finished tasks, never the one running

functasks_start

func tasks_start(place: int)

Every task starts here, on its own stack

functasks_pick

func tasks_pick(): int

The next task that may run, after the one running now. Waits, without using the processor, while every task is waiting for its time

functasks_ready

func tasks_ready(place: int, now: float): bool

functasks_left_besides

func tasks_left_besides(place: int): int

funcspawn

func spawn(work: func())

Starts work as a new task. It first runs when the task running now waits or gives others a turn

funcnext_turn

func next_turn()

Lets every other task that's ready have a turn, then carries on

funcwait_seconds

func wait_seconds(seconds: float)

Waits this many seconds, while other tasks run

funcwait_until

func wait_until(ready: func(): bool)

Waits until ready gives back true, giving other tasks turns in between, so they can make it true

functasks_left

func tasks_left(): int

How many tasks other than this one are still going

funcwait_all

func wait_all()

Waits until every other task has finished