# spawn ## Category Code Execution ## Arity **Unary** or **Binary**. ``` // Unary: no arguments spawn { code } // Binary: with arguments spawn { code } ``` ## Description Executes a code block **asynchronously** in a new fiber on the current scheduler. Returns a `ScriptHandle` immediately — the code runs concurrently. The calling fiber continues without waiting. Unlike `call`, `spawn`-executed code **can suspend** — `sleep` and `await` work inside spawned code. ## How It Works This is a **compiler-level construct**. The compiler: 1. Creates a new fiber on the current scheduler. 2. Copies the arguments (if binary) into the fiber's context. 3. Starts executing the code block. 4. Returns a `ScriptHandle` to the caller. The handle can be used to await completion, check status, or terminate the spawned code. ## Usage ### Unary spawn ```sqf _handle = spawn { sleep 5; systemChat "5 seconds passed"; }; // code continues immediately — does NOT wait for 5 seconds ``` ### Binary spawn (with args) ```sqf [100, "player"] spawn { params ["_hp", "_name"]; sleep 2; systemChat f"{_name} has {_hp} HP"; }; ``` ### Wait for completion ```sqf _handle = spawn { sleep 3; return "done"; }; _result = await _handle; // waits for handle, returns "done" ``` ### Fire-and-forget ```sqf spawn { diag_log "background task"; }; // ignore handle ``` ### Multiple parallel tasks ```sqf _handles = []; _handles pushBack (spawn { task1(); }); _handles pushBack (spawn { task2(); }); _handles pushBack (spawn { task3(); }); // Wait for all { await _x } forEach _handles; systemChat "All tasks complete"; ``` ## Return Values The spawned code's return value is stored in the ScriptHandle. Retrieve with `await`: ```sqf _handle = spawn { sleep 1; return 42; }; _val = await _handle; // 42 ``` ## Thread Safety Creates fiber on the current scheduler. The handle is owned by the spawning scheduler. Cross-scheduler spawn: use [spawnOn](spawnOn.md). ## See Also - [call](call.md) — synchronous execution - [execVM](execVM.md) — load and spawn file - [await](await.md) — wait for handle - [terminate](terminate.md) — stop spawned code - [scriptDone](scriptDone.md) — check if done - [spawnOn](spawnOn.md) — spawn on specific scheduler