Menu
Reference
- Manticore\Ds
- Async
- Classes
- AggregateError
- CancellationToken
- CancelledException
- Channel
- ChannelClosedException
- Context
- DeadlockException
- Mutex
- Once
- Pool
- Received
- SelectCase
- Selected
- Semaphore
- Settled
- Task
- TaskGroup
- TimeoutException
- Functions
- async()
- awaitAll()
- awaitAllSettled()
- awaitAny()
- channel()
- delay()
- dump()
- dumpOn()
- failure()
- group()
- mapConcurrent()
- mapSettled()
- readFile()
- select()
- selectNow()
- selectWithin()
- shield()
- shutdownOn()
- spawn()
- stats()
- timeout()
- watchdog()
- writeFile()
- Http
- Http\WebSocket
- Buffer
- Process
- Io\Poll
- Manticore\Sapi
- Ffi
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(); // 42Parameters
$fncallable- the task body
...$argsmixed- 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: 42See also: TaskGroup::spawn, Task