Skip to content

Concurrency

A PAM worker is a single PHP thread, but it is not limited to one thing at a time. Requests suspend while they wait for I/O, and inside a request you can start several futures that wait side by side. That is cooperative concurrency: only one piece of PHP runs at any instant, and control changes hands only where code waits (delay(), a socket read, await()).

This page covers the tools for coordinating that work:

  • Pam\Async\all() for fan-out and fan-in;
  • Pam\Async\Channel for passing values between futures;
  • Pam\Async\Mutex for protecting a critical section that spans a suspension point;
  • Pam\Shared\Table and task workers for state and work that cross process boundaries.

The most common pattern is “start several independent calls, wait for all of them”:

app/Http/ProductPage.php
use Pam\Http\Client;
use function Pam\Async\all;
use function Pam\Async\async;
$client = new Client(timeout: 3.0);
$results = all([
'product' => async(static fn () => $client->get("https://catalog.example.com/products/{$id}")->json()),
'stock' => async(static fn () => $client->get("https://stock.example.com/items/{$id}")->json()),
'reviews' => async(static fn () => $client->get("https://reviews.example.com/products/{$id}")->json()),
]);
// $results['product'], $results['stock'], $results['reviews']

all() returns the results with the keys you gave it. If any future throws, all() rethrows that exception; the other futures are cancelled when the request ends.

Starting a thousand futures at once also opens a thousand sockets. Process large lists in fixed-size batches:

use function Pam\Async\all;
use function Pam\Async\async;
$results = [];
foreach (array_chunk($urls, 10, preserve_keys: true) as $batch) {
$results += all(array_map(
static fn (string $url) => async(static fn () => $client->get($url)->status),
$batch,
), timeout: 5.0);
}

There is no built-in race(). Use a timeout on the primary call and fall back explicitly:

use function Pam\Async\async;
use function Pam\Async\await;
try {
$rates = await(async(static fn () => $primary->get($ratesUrl)->json()), timeout: 0.3);
} catch (RuntimeException) {
$rates = $cache->get('rates'); // last known value
}

A Pam\Async\Channel is a FIFO queue that futures use to hand values to each other:

public function __construct(int $capacity = 0);
public function send(mixed $value): void; // waits while a bounded channel is full
public function receive(): mixed; // waits while empty; returns null once closed and drained
public function close(): void;

A capacity of 0 (the default) means unbounded. With a positive capacity, send() waits until the receiver has taken a value, which gives you backpressure between a fast producer and a slow consumer.

routes/import.php
use Pam\Async\Channel;
use function Pam\Async\all;
use function Pam\Async\async;
$channel = new Channel(capacity: 2);
$producer = async(static function () use ($channel): void {
foreach ([1, 2, 3, 4] as $number) {
$channel->send($number);
}
$channel->close();
});
$consumer = async(static function () use ($channel): array {
$received = [];
while (($value = $channel->receive()) !== null) {
$received[] = $value;
}
return $received;
});
[, $received] = all([$producer, $consumer]);
// [1, 2, 3, 4]

Keep these rules in mind:

  • Run both sides as futures and wait for them together. Futures only advance while someone is inside await()/all(), so a request Fiber that calls receive() directly while the producer is an un-awaited future will wait until the request times out.
  • receive() returns null when the channel is closed and empty, so do not send null as a value.
  • send() on a closed channel throws RuntimeException('Cannot send to a closed channel.').
  • A channel lives in one worker’s memory and one request’s scheduler. It is not a queue between requests or processes.

Because PHP only switches between futures where code waits, a block with no suspension points is already atomic. You need a Pam\Async\Mutex only when a critical section itself waits, for example “read, call an API, write”:

use Pam\Async\Mutex;
use function Pam\Async\all;
use function Pam\Async\async;
use function Pam\Async\delay;
$mutex = new Mutex();
$log = [];
$jobs = [];
foreach (['x', 'y'] as $name) {
$jobs[] = async(static function () use ($mutex, &$log, $name): void {
$mutex->synchronized(static function () use (&$log, $name): void {
$log[] = "{$name}:start";
delay(0.05);
$log[] = "{$name}:end";
});
});
}
all($jobs);
// ["x:start", "x:end", "y:start", "y:end"]

synchronized() returns the callable’s result and always releases the lock, even when the callable throws.

Futures, channels and mutexes are request-scoped. When requests or workers need to share data, pick the right layer:

You need Use
A counter or small record visible to every worker of a cluster Pam\Shared\Table
Heavy or slow work off the HTTP workers Task workers
An external command or a blocking extension ProcessPool
Durable queues, cross-server locks Redis or your database (Redis, Database)

Static properties and globals are shared by every request on a worker, and several suspended requests can interleave. Never store per-request data there; use FiberContext instead. See Memory & State for the full list of pitfalls.