Runtime API Reference

Async task executor with cooperative scheduling and I/O reactor support

Import

U std/runtime

Constants

Task Status

NameValueDescription
TASK_PENDING0Task not yet started or waiting
TASK_RUNNING1Task currently executing
TASK_READY2Task ready to be polled (I/O available)
TASK_COMPLETED3Task finished successfully

Runtime Limits

NameValueDescription
MAX_TASKS256Maximum concurrent tasks

Event Loop Constants

NameValueDescription
EVFILT_READ-1Read filter for kqueue
EVFILT_WRITE-2Write filter for kqueue
EVFILT_TIMER-7Timer filter for kqueue
EV_ADD1Add event to kqueue
EV_DELETE2Delete event from kqueue
EV_ONESHOT16One-shot event flag
MAX_EVENTS64Max events per kevent call
WAKER_TOKEN-999Special token for waking event loop

Event Source Types

NameValueDescription
SOURCE_FD_READ1Waiting for readable file descriptor
SOURCE_FD_WRITE2Waiting for writable file descriptor
SOURCE_TIMER3Waiting for timer deadline

Structs

TaskNode

Represents a spawned async task in the executor.

Fields:

  • id: i64 - Unique task identifier
  • future_ptr: i64 - Pointer to future state
  • poll_fn: i64 - Function pointer for polling
  • status: i64 - Current task status
  • result: i64 - Task result value
  • next: i64 - Next task in linked list
MethodSignatureDescription
newF new(id: i64, future_ptr: i64, poll_fn: i64) -> TaskNodeCreate new task node
is_completedF is_completed(&self) -> i64Check if task completed
is_pendingF is_pending(&self) -> i64Check if task pending

JoinHandle

Handle returned when spawning a task, used to await results.

Fields:

  • task_id: i64 - Task identifier
  • task_ptr: i64 - Pointer to TaskNode
MethodSignatureDescription
newF new(task_id: i64, task_ptr: i64) -> JoinHandleCreate join handle

Runtime

Single-threaded async task scheduler (cooperative multitasking).

Fields:

  • task_count: i64 - Number of active tasks
  • next_task_id: i64 - Counter for task IDs
  • head: i64 - First task in queue
  • tail: i64 - Last task in queue
  • current_task: i64 - Currently executing task
MethodSignatureDescription
newF new() -> RuntimeCreate new runtime
spawnF spawn(&self, future_ptr: i64, poll_fn: i64) -> JoinHandleSpawn task, returns handle
runF run(&self) -> i64Run all tasks to completion
block_onF block_on(&self, future_ptr: i64, poll_fn: i64) -> i64Block on single future

EventLoop

I/O reactor using kqueue (macOS/BSD) or epoll (Linux).

Fields:

  • kq: i64 - kqueue file descriptor
  • waker_read_fd: i64 - Pipe read end for waking
  • waker_write_fd: i64 - Pipe write end
  • sources_head: i64 - Event source list head
  • sources_tail: i64 - Event source list tail
  • source_count: i64 - Number of registered sources
  • events_buf: i64 - Buffer for kevent results
  • running: i64 - 1 if loop is active
MethodSignatureDescription
newF new() -> EventLoopCreate event loop
register_readF register_read(&self, fd: i64, task_ptr: i64) -> i64Wait for fd to be readable
register_writeF register_write(&self, fd: i64, task_ptr: i64) -> i64Wait for fd to be writable
register_timerF register_timer(&self, timer_id: i64, delay_ms: i64, task_ptr: i64) -> i64Wait for timer
deregisterF deregister(&self, fd: i64, filter: i64) -> i64Remove event source
wakeF wake(&self) -> i64Wake up event loop
poll_eventsF poll_events(&self, timeout_ms: i64) -> i64Poll for I/O events
event_fdF event_fd(&self, index: i64) -> i64Get fd from event
event_filterF event_filter(&self, index: i64) -> i64Get filter from event
find_task_for_fdF find_task_for_fd(&self, fd: i64) -> i64Find waiting task
cleanupF cleanup(&self) -> i64Free all resources

ReactorRuntime

Async executor combined with I/O event loop (event-driven scheduling).

Fields:

  • task_count: i64 - Number of active tasks
  • next_task_id: i64 - Task ID counter
  • head: i64 - Task queue head
  • tail: i64 - Task queue tail
  • current_task: i64 - Currently running task
  • event_loop: i64 - Pointer to EventLoop
  • next_timer_id: i64 - Timer ID counter
MethodSignatureDescription
newF new() -> ReactorRuntimeCreate reactor runtime
spawnF spawn(&self, future_ptr: i64, poll_fn: i64) -> JoinHandleSpawn task
get_event_loopF get_event_loop(&self) -> i64Get event loop pointer
wait_readableF wait_readable(&self, fd: i64) -> i64Wait for readable
wait_writableF wait_writable(&self, fd: i64) -> i64Wait for writable
sleep_msF sleep_ms(&self, delay_ms: i64) -> i64Sleep for milliseconds
runF run(&self) -> i64Run all tasks with I/O
block_onF block_on(&self, future_ptr: i64, poll_fn: i64) -> i64Block on future with I/O

TaskGroup

Structured concurrency: spawn and manage a group of tasks. All tasks must complete before the group completes.

Fields:

  • name: i64 - Name pointer (for debugging)
  • head: i64 - Task entry list head
  • tail: i64 - Task entry list tail
  • task_count: i64 - Total tasks spawned
  • completed_count: i64 - Tasks completed
  • cancelled: i64 - 1 if group cancelled
  • cancel_on_error: i64 - Cancel siblings on error
  • results: i64 - Results array pointer
  • max_concurrency: i64 - Max concurrent tasks (0 = unlimited)
MethodSignatureDescription
newF new() -> TaskGroupCreate task group
namedF named(name_ptr: i64) -> TaskGroupCreate named group
set_cancel_on_errorF set_cancel_on_error(&self, enabled: i64) -> i64Enable/disable error cancellation
set_max_concurrencyF set_max_concurrency(&self, max: i64) -> i64Set concurrency limit
spawnF spawn(&self, future_ptr: i64, poll_fn: i64) -> i64Spawn task into group
runF run(&self) -> i64Run all tasks (0=success, 1=error)
cancelF cancel(&self) -> i64Cancel entire group
cancel_remainingF cancel_remaining(&self) -> i64Cancel pending tasks
completedF completed(&self) -> i64Get completed count
totalF total(&self) -> i64Get total task count
is_doneF is_done(&self) -> i64Check if all done
is_cancelledF is_cancelled(&self) -> i64Check if cancelled
resultF result(&self, index: i64) -> i64Get result by index
has_errorF has_error(&self, index: i64) -> i64Check error by index
task_statusF task_status(&self, index: i64) -> i64Get status by index
cleanupF cleanup(&self) -> i64Free all entries

ScopedTask

Scoped task runner that guarantees cleanup on completion.

Fields:

  • group: i64 - Pointer to TaskGroup
MethodSignatureDescription
newF new() -> ScopedTaskCreate scoped task
spawnF spawn(&self, future_ptr: i64, poll_fn: i64) -> i64Spawn task
run_and_cleanupF run_and_cleanup(&self) -> i64Run and cleanup

Global Functions

Basic Runtime

FunctionSignatureDescription
runtime_initF runtime_init() -> i64Initialize global runtime
get_runtimeF get_runtime() -> i64Get global runtime
spawnF spawn(future_ptr: i64, poll_fn: i64) -> JoinHandleSpawn on global runtime
block_onF block_on(future_ptr: i64, poll_fn: i64) -> i64Block on global runtime
run_allF run_all() -> i64Run all spawned tasks

Reactor Runtime

FunctionSignatureDescription
reactor_initF reactor_init() -> i64Initialize global reactor
get_reactorF get_reactor() -> i64Get global reactor
reactor_spawnF reactor_spawn(future_ptr: i64, poll_fn: i64) -> JoinHandleSpawn on reactor
reactor_block_onF reactor_block_on(future_ptr: i64, poll_fn: i64) -> i64Block on reactor
reactor_runF reactor_run() -> i64Run reactor event loop
wait_readableF wait_readable(fd: i64) -> i64Wait for readable
wait_writableF wait_writable(fd: i64) -> i64Wait for writable
sleep_msF sleep_ms(delay_ms: i64) -> i64Sleep milliseconds

Structured Concurrency

FunctionSignatureDescription
task_groupF task_group() -> TaskGroupCreate task group
task_group_namedF task_group_named(name_ptr: i64) -> TaskGroupCreate named group
scoped_taskF scoped_task() -> ScopedTaskCreate scoped task

Usage

Basic Async Runtime

U std/runtime

# Initialize runtime
runtime_init()

# Spawn tasks
handle := spawn(future_ptr, poll_fn)

# Run until completion
run_all()

I/O Reactor Runtime

U std/runtime

# Initialize reactor
reactor_init()

# Spawn I/O tasks
handle := reactor_spawn(future_ptr, poll_fn)

# Wait for I/O events
reactor_run()

Structured Concurrency

U std/runtime

F main() -> i64 {
    group := task_group()
    group.set_cancel_on_error(1)

    # Spawn multiple tasks
    group.spawn(future1, poll_fn1)
    group.spawn(future2, poll_fn2)
    group.spawn(future3, poll_fn3)

    # Run all to completion
    result := group.run()

    # Cleanup
    group.cleanup()

    result
}

Scoped Tasks

U std/runtime

F main() -> i64 {
    scoped := scoped_task()

    scoped.spawn(future1, poll_fn1)
    scoped.spawn(future2, poll_fn2)

    # Guaranteed cleanup even on error
    scoped.run_and_cleanup()
}

Overview

The runtime module provides three levels of async execution:

  1. Basic Runtime: Single-threaded cooperative multitasking. Tasks poll until Pending, then yield to the next task.

  2. Reactor Runtime: Event-driven I/O scheduler using kqueue/epoll. Tasks can wait for file descriptor readiness, timers, and other events.

  3. Structured Concurrency: TaskGroup and ScopedTask ensure all spawned tasks complete before the scope exits, preventing orphaned tasks.

All runtimes use cooperative scheduling: tasks must explicitly yield by returning Pending. This provides predictable execution without preemption.