Tasks
Spawn, join, and detach tasks, and manage their groups and task-local values. A task handle is consumed by one successful join or one detach.
On this page
Tasks
llam_spawn_opts_initFill spawn options with ABI-safe defaults.
int llam_spawn_opts_init(llam_spawn_opts_t *opts, size_t opts_size);Initialize spawn options to the library defaults.
This is the ABI-stable option initializer preferred by dynamic loaders and FFI bindings. LLAM writes only the overlapping prefix known to the loaded library; caller-side tail bytes from newer struct definitions are left untouched.
opts- Destination options object. Must not be NULL.
opts_size- Size of the caller's
llam_spawn_opts_tdefinition.
Returns 0 on success, -1 with errno set on invalid arguments.
llam_runtime_spawn_exSpawn into an explicit runtime handle.
llam_task_t *llam_runtime_spawn_ex(llam_runtime_t *runtime,
llam_task_fn fn,
void *arg,
const llam_spawn_opts_t *opts,
size_t opts_size);Spawn a task on an explicit runtime handle.
This is the canonical 2.x embedding entry point for host threads managing more than one runtime. The legacy llam_spawn and llam_spawn_ex wrappers still target the current managed runtime when called from a task, otherwise the default runtime. If opts supplies a cancellation token, that token must belong to runtime; a foreign-runtime token is rejected with EXDEV before the task is published. A runtime that requires asynchronous preemption rejects an unqualified entry with ENOTSUP and LLAM_SPAWN_F_NO_PREEMPT with EINVAL.
runtime- Runtime returned by
llam_runtime_create,llam_runtime_create_compatorllam_runtime_default; not NULL. fn- Task entry point. Must not be NULL.
arg- User pointer passed to
fn. opts- Optional spawn policy.
opts_size- Size of
optswhen non-NULL.
Returns Task handle on success, NULL on failure with errno set.
llam_spawn_exSpawn into the selected current/default runtime with explicit option size.
llam_task_t *llam_spawn_ex(llam_task_fn fn,
void *arg,
const llam_spawn_opts_t *opts,
size_t opts_size);Create a task and make it runnable with an explicit option size.
This is the ABI-stable form preferred by dynamic loaders and FFI bindings. LLAM copies only the overlapping prefix of opts and treats missing tail fields as spawn defaults, so older bindings can run against newer libraries that appended fields to llam_spawn_opts_t. If opts supplies a cancellation token, it must belong to the target runtime selected by this wrapper. Calls from unmanaged host threads target the default runtime and are rejected if that runtime is not initialized or is already in teardown. A runtime that requires asynchronous preemption rejects an unqualified entry with ENOTSUP and LLAM_SPAWN_F_NO_PREEMPT with EINVAL.
fn- Task entry point. Must not be NULL.
arg- User pointer passed to fn.
opts- Optional spawn options; pass NULL for defaults.
opts_size- Size of the caller's
llam_spawn_opts_tdefinition.
Returns Task handle on success, NULL on failure with errno set.
llam_spawnConvenience spawn wrapper.
llam_task_t *llam_spawn(llam_task_fn fn,
void *arg,
const llam_spawn_opts_t *opts);Create a task and make it runnable.
Legacy convenience wrapper around llam_spawn_ex. It reads only the original 32-byte options prefix for ABI compatibility; use the size-aware _ex form to supply local_executor or later option fields.
fn- Task entry point. Must not be NULL.
arg- User pointer passed to fn.
opts- Optional spawn options; pass NULL for defaults.
Returns Task handle on success, NULL on failure with errno set.
llam_joinWait indefinitely and consume a task handle on success.
int llam_join(llam_task_t *task);Wait indefinitely for task completion.
A successful join consumes task; the pointer must not be used again. Managed-task callers park cooperatively. Unmanaged OS-thread callers block until the target is already complete or another thread is actively driving llam_run; unmanaged joins do not run the scheduler. Concurrent joins on the same handle are rejected with EBUSY so the handle is consumed exactly once.
task- Task returned by llam_spawn().
Returns 0 on completion, -1 on failure with errno set.
llam_join_untilWait until an absolute deadline. A timeout leaves the handle joinable.
int llam_join_until(llam_task_t *task, uint64_t deadline_ns);Wait for task completion until an absolute deadline.
A successful timed join consumes task. If the call fails with ETIMEDOUT, the task remains joinable by the same handle. deadline_ns is an absolute llam_now_ns deadline; 0 is treated as an already-expired deadline. Concurrent joins on the same handle fail with EBUSY.
task- Task returned by llam_spawn().
deadline_ns- Absolute deadline in llam_now_ns() units.
Returns 0 on completion, -1 on timeout/failure with errno set.
llam_detachConsume a task handle without joining.
int llam_detach(llam_task_t *task);Detach a task handle so completion no longer requires join.
A successful detach consumes task; the pointer must not be used again. Detached tasks still run to completion and remain counted as live runtime work until their entry function returns. Detach fails with EBUSY if a join caller already owns the handle.
task- Task returned by llam_spawn().
Returns 0 on detach, -1 on failure with errno set.
llam_yieldCooperatively yield the current managed task.
void llam_yield(void);Cooperatively yield the current task.
Calls outside a managed LLAM task are a no-op.
llam_task_safepointMark progress in CPU-bound loops.
void llam_task_safepoint(void);Execute a cooperative safepoint without requiring an immediate yield.
CPU-bound managed tasks should call this periodically from long loops so the watchdog, cancellation, allocator quiescence, and cooperative preemption machinery can observe progress. Calls outside a managed LLAM task are a no-op.
LLAM_PREEMPT_POLLPublic hot-loop safepoint macro.
#define LLAM_PREEMPT_POLL()Low-overhead preemption poll for CPU-bound loops.
This macro intentionally expands to the public safepoint API so callers do not depend on private scheduler state. It is safe outside managed LLAM tasks and becomes a no-op there.
LLAM_PREEMPT_POLL_EVERYSafepoint macro for counted loops. Arguments are evaluated once.
#define LLAM_PREEMPT_POLL_EVERY(counter, interval)Poll for cooperative preemption every interval loop iterations.
counter is evaluated once. interval values 0 and 1 poll every call. Use this in tight CPU loops that would otherwise not call any LLAM API.
llam_task_set_classChange the current task scheduler class.
int llam_task_set_class(uint32_t task_class);Change the current task's scheduler class using a llam_task_class_t value.
Returns 0 on success, -1 with errno set to EINVAL or ENOTSUP.
Task results
llam_task_set_resultPublish an application value and error at completion.
int llam_task_set_result(void *value, int32_t application_error);Set the current task's result. The runtime does not destroy the value.
value- Application-owned value; NULL is a valid result.
application_error- Application error, independent of runtime
errno.
Returns 0 on success, -1 with errno set to ENOTSUP outside a managed task.
llam_join_resultWait, copy the result, and consume a normal handle. An unsuccessful join leaves output untouched.
int llam_join_result(llam_task_t *task,
llam_task_result_t *out,
size_t out_size);Consume a normal joinable handle and copy its result; runtime failure leaves output untouched.
task- Joinable task handle, consumed on success.
outout- Receives the result. Must not be NULL.
out_size- Size of the caller's
llam_task_result_t; must be nonzero.
Returns 0 on success, -1 with errno set.
llam_join_result_untilSame, until an absolute deadline. A timeout leaves the handle joinable.
int llam_join_result_until(llam_task_t *task,
uint64_t deadline_ns,
llam_task_result_t *out,
size_t out_size);Consume a normal joinable handle and copy its result; runtime failure leaves output untouched.
task- Joinable task handle, consumed on success.
deadline_ns- Absolute
llam_now_nsdeadline; 0 is already expired. A timeout leaves the handle joinable. outout- Receives the result. Must not be NULL.
out_size- Size of the caller's
llam_task_result_t; must be nonzero.
Returns 0 on success, -1 with errno set.
llam_task_get_resultPeek after completion, including at a borrowed group child.
int llam_task_get_result(llam_task_t *task,
llam_task_result_t *out,
size_t out_size);Peek at a completed task, including a borrowed group child; EAGAIN until completed.
task- Task handle; not consumed.
outout- Receives the result, left unchanged on failure. Must not be NULL.
out_size- Size of the caller's
llam_task_result_t; must be nonzero.
Returns 0 on success, -1 with errno set.
Task groups
llam_task_group_createLegacy group: explicit child tokens override group cancellation.
llam_task_group_t *llam_task_group_create(void);Create a structured task group.
A group owns the task handles spawned through it. Use llam_task_group_join to consume all child handles, or llam_task_group_cancel to request cooperative cancellation first. Group cancellation is delivered through the group's own token; children spawned with an explicit caller-owned token remain controlled by that token. The create_ex forms can opt in to LLAM_TASK_GROUP_F_LINK_CANCEL (group OR external).
llam_task_group_create_exOpt in to LLAM_TASK_GROUP_F_LINK_CANCEL: group OR explicit token.
llam_task_group_t *llam_task_group_create_ex(
const llam_task_group_opts_t *opts,
size_t opts_size);Create a task group from options, on the current task's or default runtime.
opts- Optional group options; NULL selects no flags, which is
llam_task_group_create. opts_size- Size of
optswhen non-NULL; must then be nonzero.
Returns New handle, or NULL with errno set.
llam_runtime_task_group_create_exOpt in to LLAM_TASK_GROUP_F_LINK_CANCEL: group OR explicit token.
llam_task_group_t *llam_runtime_task_group_create_ex(
llam_runtime_t *runtime,
const llam_task_group_opts_t *opts,
size_t opts_size);Create a task group from options, owned by an explicit runtime.
runtime- Initialized runtime that will own the group; not NULL.
opts- Optional group options; NULL selects no flags.
opts_size- Size of
optswhen non-NULL; must then be nonzero.
Returns New handle, or NULL with errno set.
llam_task_group_spawn_exSpawn a grouped child with explicit option size.
llam_task_t *llam_task_group_spawn_ex(llam_task_group_t *group,
llam_task_fn fn,
void *arg,
const llam_spawn_opts_t *opts,
size_t opts_size);Spawn a task owned by a group with explicit option size.
If opts does not provide a cancellation token, the group cancellation token is attached automatically. The returned task pointer is borrowed for diagnostics; regular llam_join and llam_detach reject it with EBUSY so only the owning group can consume the child handle. The child is marked as group-owned before it can execute, so a self-join/self-detach path cannot consume the borrowed handle first. Spawning while another thread is joining the group fails with EBUSY. Calls racing with a completed group destroy fail with EINVAL instead of dereferencing a reclaimed handle. A saturated public-operation lifecycle sentinel also fails closed with EBUSY. Children are always spawned on the group's owner runtime, including when the caller is an unmanaged host thread.
group- Group that will own the child; not NULL.
fn- Task entry point. Must not be NULL.
arg- User pointer passed to
fn. opts- Optional spawn options; pass NULL for defaults.
opts_size- Size of
optswhen non-NULL.
Returns Borrowed task handle, or NULL with errno set.
llam_task_group_spawn_result_exReturn the spawn error number directly and provide the borrowed child handle through an output pointer.
int llam_task_group_spawn_result_ex(llam_task_group_t *group,
llam_task_fn fn,
void *arg,
const llam_spawn_opts_t *opts,
size_t opts_size,
llam_task_t **out);Spawn with the same semantics as llam_task_group_spawn_ex.
Returns Zero with a borrowed handle in out, or the error number directly with out cleared. out must be non-NULL. Calls from a guarded native callback return ENOTSUP before accessing out.
llam_task_group_spawnConvenience grouped spawn wrapper.
llam_task_t *llam_task_group_spawn(llam_task_group_t *group,
llam_task_fn fn,
void *arg,
const llam_spawn_opts_t *opts);Spawn a task owned by a group.
Reads only the original 32-byte spawn-options prefix. Use llam_task_group_spawn_ex to supply local_executor or later option fields.
llam_task_group_cancelCancel the group source; external tokens themselves are never cancelled.
int llam_task_group_cancel(llam_task_group_t *group);Request cooperative cancellation for children using the group token.
The group cancels the token automatically attached to children that did not provide opts.cancel_token. It does not cancel caller-owned explicit tokens, because those tokens may be shared with tasks outside the group.
llam_task_group_joinJoin all grouped children.
int llam_task_group_join(llam_task_group_t *group);Join all tasks owned by a group.
Successful joins consume the child task handles. If an error occurs, the failed and remaining handles stay owned by the group. The function fails with EBUSY while another spawn or join is in progress for the same group.
llam_task_group_join_untilJoin grouped children until an absolute deadline.
int llam_task_group_join_until(llam_task_group_t *group,
uint64_t deadline_ns);Join all tasks owned by a group until an absolute deadline.
deadline_ns is an absolute llam_now_ns deadline. 0 is treated as an already-expired deadline, matching llam_join_until. Successful joins consume completed child task handles. If the deadline expires or another join error occurs, the failed and remaining handles stay owned by the group. The function fails with EBUSY while another spawn or join is in progress for the same group.
Returns 0 when every child was joined, or -1 with errno set.
llam_task_group_drainSeal admission and wait for actual child/native retirement while deferring caller cancellation and deadlines, including during runtime stop.
int llam_task_group_drain(llam_task_group_t *group);Seal group admission and drain actual child execution before consuming every child handle. Caller cancellation and request deadlines are deferred, not cleared; runtime stop still allows existing children and this wait to progress. Managed callers park. A child cannot drain its own group (EDEADLK), and host callers need an active runner for pending work (EBUSY). Sealed spawns fail with EPIPE. Existing join APIs remain interruptible and leave admission reusable. Zero proves quiescence. A fatal runtime error does NOT authorize releasing borrowed captures/stacks: the caller must retain them or terminate, never unwind borrowed storage as if drain succeeded. No timeout variant is provided.
llam_task_group_destroyDestroy a group after child work is drained or cancelled.
int llam_task_group_destroy(llam_task_group_t *group);Destroy an empty task group.
Returns 0 on success, or -1 with errno set to EBUSY if unjoined tasks remain, another thread is currently spawning/cancelling through the group, or a group join is in progress.
Task-local storage
llam_task_local_key_createAllocate a task-local storage key.
int llam_task_local_key_create(llam_task_local_key_t *out_key);out_keyout- Receives the key; set to
LLAM_TASK_LOCAL_INVALID_KEYon failure. Must not be NULL.
Returns 0 on success, -1 with errno set.
llam_task_local_key_deleteDelete a task-local storage key.
int llam_task_local_key_delete(llam_task_local_key_t key);Existing per-task values for the key are discarded when each task exits or sets the key to NULL.
llam_task_local_getRead the current task's value for a key.
void *llam_task_local_get(llam_task_local_key_t key);Return the current task's value for a task-local key.
Must be called from a managed LLAM task; outside task context sets errno to ENOTSUP and returns NULL.
llam_task_local_setSet or clear the current task's value for a key.
int llam_task_local_set(llam_task_local_key_t key, void *value);Set the current task's value for a task-local key.
Passing NULL clears the key for the current task. Must be called from a managed LLAM task.
llam_task_local_set_ownedInstall a value at an empty key, with a nonblocking cleanup that runs at task exit.
int llam_task_local_set_owned(llam_task_local_key_t key,
void *value,
llam_task_cleanup_fn cleanup);Install ownership at an empty key (EBUSY if populated).
cleanup must be non-NULL for a non-NULL value, must return normally, must not block or call LLAM task/wait APIs. It runs once before completion is published, including after cancellation. NATIVE_AFFINE tasks retain native-M identity. Portable and compatibility tasks use their exit worker and require a thread-neutral cleanup. Uncertified asynchronous tasks fail ENOTSUP. Plain set cannot overwrite an owned entry; take first to transfer ownership. Key deletion never suppresses an already registered cleanup.
key- Active key with no value for this task.
value- Owned value. Must not be NULL.
cleanup- Called once with
valuewhen the task exits. Must not be NULL.
Returns 0 on success, -1 with errno set.
llam_task_local_take_resultRemove a value and transfer its ownership without running cleanup.
int llam_task_local_take_result(llam_task_local_key_t key, void **out);Remove a current-task value without cleanup; a missing active key succeeds with NULL.
key- Task-local key.
outout- Receives the value, and is set to NULL first. Must not be NULL.
Returns 0 on success, -1 with errno set to EINVAL for an inactive key or ENOTSUP outside a managed task.
LLAM_TASK_LOCAL_INVALID_KEYInvalid key sentinel.
#define LLAM_TASK_LOCAL_INVALID_KEYInvalid task-local storage key value.
Development: borrowed group drain
ABI 2.6 adds llam_task_group_drain for structured scopes whose children borrow
parent storage. It seals admission (EPIPE on subsequent spawns), includes spawn
reservations already accepted, parks managed callers and consumes all child
handles only after actual execution retirement. Caller cancellation and request
deadlines are deferred and restored; existing children continue cleanup during
runtime stop. Ordinary group join retains its interruptible, reusable contract.
There is deliberately no timed borrowed drain. Only a zero return authorizes releasing borrowed captures/stacks. A fatal runtime error does not establish quiescence: retain storage or terminate rather than unwinding it as though cleanup succeeded. Invalid/stale handles, wrong owners, a child draining its own group, and missing host runners are diagnosed. A host drain does not drive the scheduler. The owned scope deadline API is suitable when ownership can remain outstanding after timeout; it does not establish a borrowed lexical lifetime.