Menu

Reference / Async

spawn()

function
function spawn(callable $fn, mixed ...$args): Task

Spawn a concurrent task into the scope open in the calling task and return a handle.

Never fire-and-forget: the task is owned by, and joined at the end of, that scope. The new task starts when the calling task next suspends. To spawn into a specific scope use $group->spawn().

$t = Async\spawn(fn($x) => $x * 2, 21);
echo $t->await();   // 42

Parameters

$fn callable
the task body
...$args mixed
passed to $fn

Returns

Task — the handle; await() it or let the scope join it

Throws

\LogicException
outside async(), where there is no scope to own the task

Example

use function Async\async;
use function Async\delay;
use function Async\spawn;

// async() runs the callable on the engine and returns its value.
$total = async(function () {
    // spawn() starts a task in the current scope and returns a handle.
    $slow = spawn(function () {
        delay(0.02);
        return 10;
    });
    $fast = spawn(function () {
        delay(0.01);
        return 32;
    });

    // await() suspends this task (not the process) until the other one settles.
    return $slow->await() + $fast->await();
});

echo "total: $total\n";

Output

total: 42

See also: TaskGroup::spawn, Task

View source