Real OS threads for HolyPHP with Go-style channels, mutexes,
atomics, barriers and a worker Pool. Shared state is discouraged by design —
communicate by sending messages over channels.
stdlib — embeddedreal OS threadsGo-style channelsparallel_mapno data races by design
Primitives at a glance
Primitive
What it does
thr_spawn($fn)
run a closure on a new OS thread
thr_join($t)
wait for a thread to finish
thr_parallel_map($fn, $arr)
map a closure over an array on all cores, order preserved
chan_new($cap) / chan_send / chan_recv
Go-style channels — rendezvous or buffered ring; chan_close + drained receives like Go
mutex_new / mutex_lock / mutex_unlock
mutual exclusion (with a Mutex::synchronized wrapper class)
atomic_new / atomic_add / atomic_get
mutex-backed 64-bit counters, safe across threads
barrier_new($n) / barrier_wait
release N threads together, arrival indexes like pthreads
map a closure over an array on all cores, order preserved
chan_new($cap) / chan_send / chan_recv
Go-style channels — rendezvous or buffered ring; chan_close + drained receives like Go
mutex_new / mutex_lock / mutex_unlock
mutual exclusion (with a Mutex::synchronized wrapper class)
atomic_new / atomic_add / atomic_get
mutex-backed 64-bit counters, safe across threads
barrier_new($n) / barrier_wait
release N threads together, arrival indexes like pthreads
thr_cpu_count()
number of usable cores
Channels: the preferred style
import "thread";
$ch = chan_new(4); // buffered channel
thr_spawn(function() use ($ch) {
foreach (["scan", "parse", "index"] as $step) {
chan_send($ch, $step . " done");
}
chan_close($ch); // no more sends
});
while (true) {
$msg = chan_recv($ch);
if ($msg === false) { break; } // closed and drained
echo $msg;
}
Rule: captured arrays and objects are COW copies — each
thread sees its own snapshot. Never write one captured array from several
threads; send results back through a channel instead. That single rule is why
there are no data races to debug.
Parallel map, one call
import "thread";
$squares = thr_parallel_map(function($x) { return $x * $x; }, [1,2,3,4,5]);
// [1, 4, 9, 16, 25] — input order kept regardless of finish order
// chunked variant for big inputs: strided workers + channel collection
$out = thr_map_chunked($bigArray, function($x) { return heavy($x); }); // items first, then the function
The Pool class
import "thread";
$pool = new Pool(4); // 4 workers
// one call: every item through the function, results in input order
$sizes = $pool->map(function($url) {
return strlen(file_get_contents($url));
}, $urls);
Known issue: the streaming form $pool->start($fn) followed by
submit() crashes at run time in this release, as does new Thread($fn) with
arguments passed to start(). Use Pool::map, thr_parallel_map,
thr_map_chunked or thr_spawn until the fix ships.
Concurrency + event loop
Threads and async compose: run a blocking fetch
or a private loop on a worker thread, deliver the outcome through a channel,
and the main loop never stalls.
import "async";
import "thread";
$ch = chan_new(1);
thr_spawn(function() use ($ch) {
async_get("http://slow.service/", function($r) use ($ch) {
chan_send($ch, strlen($r));
});
});
$lp = new Loop();
$lp->every(100, function() use ($ch, $lp) {
$n = chan_try_recv($ch);
if ($n !== false) { echo "fetched $n bytes"; $lp->stop(); }
});
$lp->run();
Examples
5 complete programs. Every one is type-checked with the compiler before the site is published; copy one into src/ of a project (hphp create) and run it.
01Producer and consumer over a channel
Two threads, one channel between them. The producer thread sends work items and closes the channel when it is done; the main thread receives until chan_recv() returns false, which means "closed and fully drained". This is the Go pattern, and the safest way to share data: nothing is shared, values are copied through the channel.
A thread closure may only capture plain values, so threads talk through the channel id returned by chan_new().
01-producer-consumer.hphp
<?php
import "thread";
// A buffered channel: the producer can run up to 3 orders ahead.
$orders = chan_new(3);
// The producer runs on its own OS thread.
$producer = thr_spawn(function() use ($orders) {
$menu = ["espresso", "latte", "cappuccino", "flat white", "mocha"];
foreach ($menu as $index => $drink) {
thr_sleep_ms(100);
chan_send($orders, ["number" => $index + 1, "drink" => $drink]);
echo " [producer] queued order " . ($index + 1);
}
chan_close($orders);
});
// The consumer (main thread) handles orders until the channel is drained.
$served = 0;
while (true) {
$order = chan_recv($orders);
if ($order === false) {
break;
}
thr_sleep_ms(150);
echo "[barista] order " . $order["number"] . ": one " . $order["drink"];
$served = $served + 1;
}
thr_join($producer);
echo "all done - served $served orders";
Try it
hphp run 01-producer-consumer.hphp
02Counting primes on every core
Pool::map() runs a function over an array on several OS threads and returns the results in input order, whatever order the threads finish in. Here the range 1..2,000,000 is cut into eight slices, the slices are counted on worker threads, and the time is compared with doing the same work on one thread.
02-parallel-map.hphp
<?php
import "thread";
// Plain, deliberately slow trial division: good CPU-bound work.
function count_primes(int $from, int $to): int {
$found = 0;
for ($n = $from; $n <= $to; $n++) {
if ($n < 2) {
continue;
}
$isPrime = true;
for ($d = 2; $d * $d <= $n; $d++) {
if ($n % $d == 0) {
$isPrime = false;
break;
}
}
if ($isPrime) {
$found = $found + 1;
}
}
return $found;
}
// Cut the range into 8 equal slices.
$limit = 2000000;
$sliceCount = 8;
$sliceSize = intdiv($limit, $sliceCount);
$slices = [];
for ($start = 1; $start <= $limit; $start += $sliceSize) {
$slices[] = [$start, min($start + $sliceSize - 1, $limit)];
}
// Parallel: up to one worker thread per core, one slice per job.
$workers = min(thr_cpu_count(), $sliceCount);
$pool = new Pool($workers);
$t0 = microtime();
$counts = $pool->map(function($slice) {
return count_primes($slice[0], $slice[1]);
}, $slices);
$parallelMs = intval((microtime() - $t0) * 1000);
foreach ($slices as $i => $slice) {
echo "slice " . $slice[0] . ".." . $slice[1] . ": " . $counts[$i] . " primes";
}
echo "parallel: " . array_sum($counts) . " primes in $parallelMs ms on $workers threads";
// Sequential: the same work on the main thread, for comparison.
$t1 = microtime();
$total = count_primes(1, $limit);
$sequentialMs = intval((microtime() - $t1) * 1000);
echo "sequential: $total primes in $sequentialMs ms on 1 thread";
Try it
hphp run 02-parallel-map.hphp
03A worker pool from channels
The classic pool: a fixed number of workers pull jobs from a shared jobs channel and push answers onto a results channel. Closing the jobs channel is the "no more work" signal - each worker's chan_recv() then returns false and the worker exits. Results come back in finish order, so every result carries the id of its job.
03-worker-pool.hphp
<?php
import "thread";
// The job: count the words of one document and find the longest one.
function analyse(string $text) {
$words = preg_split("/[^a-z]+/", strtolower($text));
$total = 0;
$longest = "";
foreach ($words as $word) {
if ($word == "") {
continue;
}
$total = $total + 1;
if (strlen($word) > strlen($longest)) {
$longest = $word;
}
}
return ["words" => $total, "longest" => $longest];
}
$documents = [
"The quick brown fox jumps over the lazy dog, and the fox runs away.",
"Threads share nothing here: every message is copied through a channel.",
"Workers pull jobs, workers push results, workers stop when closed.",
"Buffered channels let the sender run ahead of a slow receiver.",
];
// Both channels are big enough to hold every job, so sends never block.
$jobs = chan_new(count($documents));
$results = chan_new(count($documents));
// Start three workers. Each one loops until the jobs channel is closed.
$workerCount = 3;
for ($w = 1; $w <= $workerCount; $w++) {
thr_spawn(function() use ($w, $jobs, $results) {
while (true) {
$job = chan_recv($jobs);
if ($job === false) {
break;
}
$stats = analyse($job["text"]);
chan_send($results, ["id" => $job["id"], "worker" => $w, "stats" => $stats]);
}
});
}
// Queue every document, then announce that no more jobs will come.
foreach ($documents as $id => $text) {
chan_send($jobs, ["id" => $id, "text" => $text]);
}
chan_close($jobs);
// Collect exactly one result per document.
for ($i = 0; $i < count($documents); $i++) {
$result = chan_recv($results);
$stats = $result["stats"];
echo "doc " . $result["id"] . " (worker " . $result["worker"] . "): "
. $stats["words"] . " words, longest word: " . $stats["longest"];
}
Try it
hphp run 03-worker-pool.hphp
04A foot race: barrier, atomic and mutex
Four runner threads line up at a Barrier, so they all start at the same instant. Each runs for a random time, then takes the next place from an Atomic counter - an increment that is exact even when threads finish at the same moment. A Mutex keeps their console lines from interleaving, and the results travel back to the main thread over a channel.
The objects are created on the main thread; a thread closure captures only their integer ids and uses the matching barrier_, atomic_ and mutex_ functions.
04-race.hphp
<?php
import "thread";
$runners = ["Ada", "Grace", "Linus", "Margaret"];
// Shared synchronisation objects, passed to threads by id.
$startLine = new Barrier(count($runners));
$places = new Atomic(0);
$console = new Mutex();
$barrierId = $startLine->id;
$placeId = $places->id;
$consoleId = $console->id;
$finished = chan_new(count($runners));
// One thread per runner.
foreach ($runners as $name) {
thr_spawn(function() use ($name, $barrierId, $placeId, $consoleId, $finished) {
// Wait until every runner is at the start line.
barrier_wait($barrierId);
// Run! Then claim the next place; atomic_add returns the old value.
thr_sleep_ms(rand(100, 400));
$place = atomic_add($placeId, 1) + 1;
// Only one thread prints at a time.
mutex_lock($consoleId);
echo " $name crosses the line";
mutex_unlock($consoleId);
chan_send($finished, [$place, $name]);
});
}
// Collect every runner, then print the podium in order.
$board = [];
for ($i = 0; $i < count($runners); $i++) {
$result = chan_recv($finished);
$board[$result[0]] = $result[1];
}
ksort($board);
echo "Results:";
foreach ($board as $place => $name) {
echo " $place. $name";
}
echo "places handed out: " . $places->get();
Try it
hphp run 04-race.hphp
05Heavy work off the event loop
An async Loop must never block, so CPU-heavy jobs go to threads. Each job runs on its own thread and reports back on a channel; the loop polls that channel with the non-blocking chan_try_recv() from a timer, while a second timer shows the loop stays responsive the whole time. When the last job is in, stop() ends the loop.
05-offload-from-event-loop.hphp
<?php
import "async";
import "thread";
// CPU-bound work: hash a string over and over.
function stretch_key(string $password, int $rounds): string {
$hash = $password;
for ($i = 0; $i < $rounds; $i++) {
$hash = sha256($hash);
}
return $hash;
}
$jobs = ["alice" => 12000, "bob" => 4000, "carol" => 8000];
$done = chan_new(count($jobs));
// Start one background thread per job.
foreach ($jobs as $user => $rounds) {
thr_spawn(function() use ($user, $rounds, $done) {
$key = stretch_key("secret-of-$user", $rounds);
chan_send($done, [$user, $rounds, substr($key, 0, 16)]);
});
}
$loop = new Loop();
$started = now_ms();
$remaining = count($jobs);
// Heartbeat: proves the loop keeps running while threads work.
$loop->every(250, function() use ($started) {
echo " ...loop alive at " . (now_ms() - $started) . " ms";
});
// Poll for finished jobs without ever blocking the loop.
$loop->every(20, function() use ($loop, $done, $started, &$remaining) {
$result = chan_try_recv($done);
if ($result === false) {
return;
}
$elapsed = now_ms() - $started;
echo $result[0] . ": " . $result[1] . " rounds -> " . $result[2] . "... ($elapsed ms)";
$remaining = $remaining - 1;
if ($remaining == 0) {
$loop->stop();
}
});
$loop->run();
echo "all keys derived";