Skip to content

spawnOn

ffredyk edited this page Jul 23, 2026 · 1 revision

spawnOn

Category

Concurrency

Arity

Unary or Binary.

// Unary: spawn on named scheduler
spawnOn ["schedulerName", { code }]

// Binary: with args
<args> spawnOn ["schedulerName", { code }]

Description

Spawns code on a specific named scheduler, rather than the current one. This enables cross-scheduler work distribution — e.g., running AI on a dedicated "AI" scheduler while keeping the "Main" scheduler responsive.

Returns a ScriptHandle owned by the current scheduler.

How It Works

  1. Looks up the scheduler by name.
  2. Creates a new fiber on that scheduler.
  3. Passes arguments (if binary form) into the fiber.
  4. Returns a handle visible to the calling scheduler.

The code runs with the target scheduler's budget and fiber management. Suspension (sleep, await) works normally inside the spawned code.

Usage

Unary spawnOn

_handle = spawnOn ["AI", {
    heavyPathfinding();
    sleep 0.1;
    heavyPathfinding();
}];

Binary spawnOn (with args)

[enemyData] spawnOn ["AI", {
    params ["_data"];
    calculateBehavior(_data);
}];

Work distribution pattern

// Main scheduler: UI, input
// "AI" scheduler: pathfinding, behavior
// "Physics" scheduler: collision, movement

for "_i" from 1 to 10 do {
    _aiUnits pushBack (spawnOn ["AI", { aiLoop(); }]);
};

Monitor spawned code

_handle = spawnOn ["Worker", { longTask(); }];
_result = await (_handle timeout 30);
if (isNil "_result") then {
    terminate _handle;
    systemChat "Worker task timed out";
};

Thread Safety

The spawned code runs on a different scheduler — thread safety rules apply. Data shared between schedulers must be frozen, sent via sendTo, or use shared variables.

See Also

SQ# Wiki

Home

Engine Docs

Migration

Commands

Value Constructors

Arithmetic

Comparison

Logic

Array

String

Math

Random

Type & Introspection

HashMap

Code Execution

Concurrency

Scheduler

Thread Safety

Error

Output

Time

Multiplayer

Compiler

Clone this wiki locally