1. Go to this page and download the library: Download hiblaphp/parallel library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
hiblaphp / parallel example snippets
use function Hibla\{parallel, await};
$result = await(parallel(function () {
return 'Hello from a separate process!';
}));
echo $result; // Hello from a separate process!
// hibla_parallel.php
use function Rcalicdan\env;
return [
/*
|--------------------------------------------------------------------------
| Maximum Nesting Level
|--------------------------------------------------------------------------
| The maximum number of parallel() calls that can be nested inside each
| other. Acts as a fork-bomb safety valve.
|
| .env variable: HIBLA_PARALLEL_MAX_NESTING_LEVEL
*/
'max_nesting_level' => env('HIBLA_PARALLEL_MAX_NESTING_LEVEL', 5),
/*
|--------------------------------------------------------------------------
| Standard Process Settings (parallel() / Parallel::task() / Parallel::pool())
|--------------------------------------------------------------------------
| .env variables:
| HIBLA_PARALLEL_PROCESS_MEMORY_LIMIT
| HIBLA_PARALLEL_PROCESS_TIMEOUT
*/
'process' => [
'memory_limit' => env('HIBLA_PARALLEL_PROCESS_MEMORY_LIMIT', '512M'),
'timeout' => env('HIBLA_PARALLEL_PROCESS_TIMEOUT', 60),
],
/*
|--------------------------------------------------------------------------
| Background Process Settings (spawn() / Parallel::background())
|--------------------------------------------------------------------------
| 'spawn_limit_per_second': Prevents fork bombs by capping how many
| background tasks can be spawned per second. Default is 50.
|
| .env variables:
| HIBLA_PARALLEL_BACKGROUND_PROCESS_MEMORY_LIMIT
| HIBLA_PARALLEL_BACKGROUND_PROCESS_TIMEOUT
| HIBLA_PARALLEL_BACKGROUND_SPAWN_LIMIT
*/
'background_process' => [
'memory_limit' => env('HIBLA_PARALLEL_BACKGROUND_PROCESS_MEMORY_LIMIT', '512M'),
'timeout' => env('HIBLA_PARALLEL_BACKGROUND_PROCESS_TIMEOUT', 600),
'spawn_limit_per_second' => env('HIBLA_PARALLEL_BACKGROUND_SPAWN_LIMIT', 50, true),
],
/*
|--------------------------------------------------------------------------
| Framework Bootstrap Configuration
|--------------------------------------------------------------------------
| Set a default bootstrap so every worker automatically loads your
| framework without calling withBootstrap() on every executor.
|
| Laravel example:
| 'bootstrap' => [
| 'file' => __DIR__ . '/bootstrap/app.php',
| 'callback' => function(string $bootstrapFile) {
| $app =
use App\Tasks\HeavyTask;
parallel([HeavyTask::class, 'run']);
// Works without an autoloader entry — the closure body is serialized and sent to the worker
parallel(function () {
return "I am self-contained logic";
});
use Hibla\Parallel\Parallel;
$pool = Parallel::pool(4)
->withBootstrap(__DIR__ . '/
use Hibla\Parallel\Parallel;
// Laravel example
$pool = Parallel::pool(8)
->withBootstrap(__DIR__ . '/bootstrap/app.php', function (string $file) {
$app =
// Symfony example
$pool = Parallel::pool(8)
->withBootstrap(__DIR__ . '/config/bootstrap.php', function (string $file) {
$multiplier = 3;
$result = await(parallel(function () use ($multiplier) {
// $multiplier = 3 is serialized with the closure and reconstructed
// in the worker. The worker never shared memory with the parent;
// it received a copy of the value.
return 6 * $multiplier; // 18
}));
// Wrong — PDO handle cannot be serialized across processes
$db = new PDO('mysql:host=localhost;dbname=app', 'user', 'pass');
$result = await(parallel(function () use ($db) {
return $db->query('SELECT ...'); // TaskPayloadException
}));
// Correct — create the connection inside the worker
$result = await(parallel(function () {
$db = new PDO('mysql:host=localhost;dbname=app', 'user', 'pass');
return $db->query('SELECT ...')->fetchAll();
}));
use function Hibla\{parallel, await};
$result = await(parallel(function () {
return strlen("Hello from the background!");
}));
echo $result; // 27
use function Hibla\{spawn, await};
// spawn() returns a Promise that resolves to a BackgroundProcess handle.
// You must await() the spawn call itself to get that handle.
$process = await(spawn(function () {
file_put_contents('log.txt', "Task started at " . date('Y-m-d H:i:s'));
sleep(5);
}));
if ($process->isRunning()) {
echo "Task is running with PID: " . $process->getPid();
}
// $process->terminate(); // kill it early if needed
use App\ValueObjects\TaskResult;
use function Hibla\{parallel, await};
$result = await(parallel(function () {
return new TaskResult(status: 'success', data: [1, 2, 3]);
}));
echo get_class($result); // "App\ValueObjects\TaskResult"
echo $result->status; // "success"
namespace App\Services;
class ReportBuilder
{
public function __construct(
private string $title = "Q4 Report",
private int $year = 2025
) {}
public function buildParallel(): string
{
return await(parallel(fn() => "{$this->title} ({$this->year})"));
}
}
$builder = new ReportBuilder();
echo $builder->buildParallel(); // "Q4 Report (2025)"
use function Hibla\{parallel, await};
$result = await(parallel(function () {
return expensiveComputation();
}, timeout: 30));
use function Hibla\{parallelFn, await};
use Hibla\Promise\Promise;
$processItem = parallelFn(function (int $id): array {
return fetchFromDatabase($id);
});
$results = await(Promise::all([
$processItem(1),
$processItem(2),
$processItem(3),
]));
use function Hibla\{spawn, await};
$process = await(spawn(function () {
generateReport();
}));
echo $process->getPid();
echo $process->isRunning() ? 'still running' : 'done';
$process->terminate(); // kill it early if needed
use Hibla\Parallel\Parallel;
use Hibla\Promise\Promise;
use function Hibla\await;
$pool = Parallel::pool(size: 4)
->withTimeout(30)
->withMemoryLimit('256M');
$processItem = $pool->runFn(function (int $id): array {
return fetchAndTransform($id);
});
$results = await(Promise::all(array_map($processItem, $ids)));
$pool->shutdown();
use Hibla\Parallel\Parallel;
use function Hibla\await;
$sendEmail = Parallel::background()
->withTimeout(120)
->withMemoryLimit('128M')
->withBootstrap('/path/to/bootstrap.php')
->spawnFn(function (string $to, string $subject): void {
Mailer::send($to, $subject);
});
await($sendEmail('[email protected]', 'Welcome!'));
await($sendEmail('[email protected]', 'Invoice'));
use Hibla\Parallel\Parallel;
use function Hibla\await;
$pool = Parallel::pool(size: 4)
->withMaxExecutionsPerWorker(100)
->withMemoryLimit('128M');
$task = fn() => getmypid();
for ($i = 0; $i < 4; $i++) {
$pool->run($task)->then(fn($pid) => print("Handled by worker: $pid\n"));
}
// Once all tasks are complete and the event loop is empty, the script will
// exit naturally. PHP's Garbage Collector will automatically tear down the
// OS processes via the pool's __destruct() method. No manual cleanup is
// Option A: Forceful Shutdown — instantly kills all workers in the pool.
// Any currently executing or queued tasks are rejected with a PoolShutdownException.
$pool->shutdown();
// Option B: Graceful Drain — stops accepting new tasks, but waits for all
// currently executing and queued tasks to finish before tearing down the workers.
$pool->drain();
$pool = Parallel::pool(size: 4)->boot();
// Blocks until all 4 workers send their READY frame.
$result = await($pool->run(fn() => heavyWork()));
async(function() use ($pool) {
$pool->boot(); // Suspends this fiber non-blocking
$result = await($pool->run(fn() => heavyWork()));
});
use Hibla\Parallel\Parallel;
use Hibla\Parallel\Interfaces\ProcessPoolInterface;
$pool = Parallel::pool(size: 4)
->withoutTimeout() // long-running workers must not have a timeout
->onWorkerRespawn(function (ProcessPoolInterface $pool) use ($serverTask) {
// Fired every time a worker exits, whether from a crash or a planned
// retirement via withMaxExecutionsPerWorker(). Re-submit your
// long-running task to the replacement worker here.
$pool->run($serverTask);
});
declare(strict_types=1);
rocessPoolInterface;
use Hibla\Parallel\Parallel;
use Hibla\Socket\SocketServer;
// Define the router as an anonymous class so it can be captured by the
// closure and serialized to each worker via opis/closure. Each worker
// receives a full copy of the class definition and instantiates it locally.
// In a real application this would be a named autoloadable class instead.
$routerClass = new class () {
private array $static = [];
public function get(string $path, callable $handler): void
{
$this->static['GET'][$path] = $handler;
}
public function dispatch(string $method, string $uri): string
{
return isset($this->static[$method][$uri])
? ($this->static[$method][$uri])()
: '404 Not Found';
}
};
// This closure is the long-running task submitted to each worker.
// It never returns — it starts a socket server and runs indefinitely.
// Hibla workers have their own event loop so this is valid:
// the worker runs its server loop cooperatively rather than blocking.
$serverTask = function () use ($routerClass) {
$pid = getmypid();
$router = new $routerClass();
$router->get('/', function () use ($pid) {
return "[Worker $pid] Hello! I am healthy and serving requests.";
});
// Visit http://127.0.0.1:8080/crash in a browser to trigger a crash.
// The delay(0.1) lets the HTTP response flush before exit() fires.
// Without it the connection would close mid-response and the browser
// would show a connection reset error instead of the acknowledgment.
$router->get('/crash', function () use ($pid) {
echo "[Worker $pid] Received suicide command! Crashing now...\n";
Hibla\delay(0.1)->then(fn () => exit(1));
return "[Worker $pid] Acknowledged. I am dying. Goodbye world.";
});
// SO_REUSEPORT allows multiple processes to bind to the same port.
// The kernel load-balances incoming connections across all bound
// workers at the TCP accept level — zero application coordination.
$server = new SocketServer('127.0.0.1:8080', [
'tcp' => ['so_reuseport' => true, 'backlog' => 65535],
]);
$server->on('connection', function ($connection) use ($router) {
$connection->on('data', function (string $rawRequest) use ($connection, $router) {
$firstLine = substr($rawRequest, 0, strpos($rawRequest, "\r\n"));
$parts = explode(' ', $firstLine);
$method = $parts[0] ?? 'GET';
$uri = explode('?', $parts[1] ?? '/')[0];
$content = $router->dispatch($method, $uri);
$response = "HTTP/1.1 200 OK\r\n"
. "Content-Type: text/plain\r\n"
. "Content-Length: " . strlen($content) . "\r\n"
. "\r\n"
. $content;
$connection->write($response);
});
});
echo "[Worker $pid] Started listening on 8080\n";
};
$poolSize = 4;
$pool = Parallel::pool(size: $poolSize)
->withoutTimeout() // server workers run indefinitely — no timeout
->onWorkerRespawn(function (ProcessPoolInterface $pool) use ($serverTask) {
// A worker crashed or retired. The pool has already spawned a
// replacement — re-submit the server task to put it to work.
echo "\n[Master] ALERT: Worker process exited! Triggering onWorkerRespawn hook...\n";
echo "[Master] Re-submitting Socket Server Task to the replacement worker.\n\n";
$pool->run($serverTask)->catch(fn (ProcessCrashedException $e) => null);
});
echo "--- Hibla Parallel: Chaos Web Server Test ---\n";
echo "[Master PID: " . getmypid() . "] Supervising $poolSize workers...\n\n";
for ($i = 0; $i < $poolSize; $i++) {
// The catch() silences ProcessCrashedException on the initial submissions.
// When a worker crashes its in-flight promise rejects with that exception.
// It is expected and already handled by onWorkerRespawn above, so there
// is nothing to act on at the call site.
$pool->run($serverTask)->catch(fn (ProcessCrashedException $e) => null);
}
use Hibla\Parallel\Parallel;
use Hibla\Parallel\Exceptions\RespawnRateLimitException;
use function Hibla\await;
$pool = Parallel::pool(size: 4)
->withMaxRestartPerSecond(5);
try {
await($pool->run(fn() => riskyWork()));
} catch (RespawnRateLimitException $e) {
// Pool detected a crash loop and shut itself down.
// All pending and queued tasks have been rejected.
echo $e->getMessage();
}
// Conservative — any sustained crash loop trips immediately
$pool = Parallel::pool(size: 4)
->withMaxRestartPerSecond(3);
// More tolerant — useful for larger pools or higher-churn workloads
$pool = Parallel::pool(size: 16)
->withMaxRestartPerSecond(10);
$pool = Parallel::pool(size: 4)
->withMaxRestartPerSecond(5)
->onWorkerRespawn(function (ProcessPoolInterface $pool) use ($task) {
// This fires for each individual respawn within the limit.
// It will NOT fire once RespawnRateLimitException shuts the pool down.
$pool->run($task);
});
use Hibla\Parallel\Parallel;
use function Hibla\await;
$pool = Parallel::pool(size: 4);
echo $pool->getWorkerCount(); // 4
// Workers are guaranteed to have sent READY frames — PIDs are authoritative
$pool = Parallel::pool(size: 4)->boot();
// These PIDs are accurate and match getmypid() inside tasks
$pids = $pool->getWorkerPids(); // [12345, 12346, 12347, 12348]
$pool->shutdown();
use function Hibla\parallel;
parallel(function () {
echo "Starting process...\n";
sleep(1);
echo "50% complete...\n";
sleep(1);
echo "Finished!\n";
});
// Parent sees each line as it is printed
use function Hibla\parallel;
parallel(function () {
// Will not reach the parent — bypasses the output buffer entirely
fwrite(STDOUT, "progress update\n");
// Will reach the parent — goes through the output buffer
echo "progress update\n";
});
use Hibla\Parallel\Parallel;
use function Hibla\emit;
Parallel::task()
->onMessage(function ($msg) {
echo "Worker says: {$msg->data}\n";
})
->run(function () {
emit("progress update");
});
use Hibla\Parallel\Parallel;
use App\Messages\ProgressUpdate;
use App\Messages\ValidationError;
use App\Messages\StageComplete;
use function Hibla\emit;
Parallel::task()
->onMessage(function ($msg) {
if ($msg->data instanceof ProgressUpdate) {
printf("Worker %d: %d%% complete\n", $msg->pid, $msg->data->percent);
} elseif ($msg->data instanceof ValidationError) {
printf("Validation failed on row %d: %s\n", $msg->data->row, $msg->data->reason);
} elseif ($msg->data instanceof StageComplete) {
printf("Stage '%s' finished in %.2fs\n", $msg->data->name, $msg->data->duration);
}
})
->run(function () {
emit(new ProgressUpdate(percent: 25));
foreach (loadRows() as $i => $row) {
if (! validate($row)) {
emit(new ValidationError(row: $i, reason: 'missing
$pool = Parallel::pool(size: 4)
->onMessage(function ($msg) {
// Pool-level handler — always starts first.
// Use this for cross-cutting concerns: logging, metrics, dashboards.
Logger::info("Worker {$msg->pid} emitted", ['data' => $msg->data]);
});
$pool->run(
function () {
Hibla\emit(new ProgressUpdate(percent: 50));
Hibla\emit(new ProgressUpdate(percent: 100));
},
onMessage: function ($msg) {
// Per-task handler — starts after the pool-level handler's first slice.
if ($msg->data instanceof ProgressUpdate) {
echo "This task is {$msg->data->percent}% done\n";
}
}
);
$pool->shutdown();
// UNSAFE — both handlers share $log and interleave at await points
$log = [];
$pool = Parallel::pool(size: 4)
->onMessage(function ($msg) use (&$log) {
$entries = $log;
await(Promise::resolved()); // yields here, per-task handler reads same stale $log
$log = [...$entries, "pool: {$msg->data}"];
});
$pool->run(
fn() => emit('event'),
onMessage: function ($msg) use (&$log) {
$entries = $log; // reads same stale value — one write is lost
await(Promise::resolved());
$log = [...$entries, "task: {$msg->data}"];
}
);
use Hibla\Sync\Mutex;
use function Hibla\await;
$log = [];
$mutex = new Mutex();
$pool = Parallel::pool(size: 4)
->onMessage(function ($msg) use (&$log, $mutex) {
await($mutex->withLock(function () use (&$log, $msg) {
$log[] = "pool: {$msg->data}";
}));
});
$pool->run(
fn() => emit('event'),
onMessage: function ($msg) use (&$log, $mutex) {
await($mutex->withLock(function () use (&$log, $msg) {
$log[] = "task: {$msg->data}";
}));
}
);
// This handler delays every task result by at least 2 seconds,
// regardless of how fast the worker finished.
$pool = Parallel::pool(size: 4)
->onMessage(function ($msg) {
sleep(2); // blocks the fiber — parent waits here before resolving
});
$pool = Parallel::pool(size: 4)
->onMessage(function ($msg) {
// Dispatches the slow work and returns immediately.
// The handler fiber completes without waiting for the write.
spawn(function () use ($msg) {
Database::insertMetric($msg->data);
});
});
use Hibla\Parallel\Parallel;
use Hibla\Promise\Promise;
use function Hibla\{parallel, async, await, delay};
$pool = Parallel::pool(size: 2);
$start = microtime(true);
Promise::all([
// One-off task via global helper
parallel(fn() => sleep(1)),
// One-off task via fluent executor
Parallel::task()->run(fn() => sleep(1)),
// Pool task — dispatched to a persistent worker
$pool->run(fn() => sleep(1)),
// Worker that internally mixes parallel tasks with async fibers
parallel(function () {
await(Promise::all([
async(fn() => await(delay(1))),
async(fn() => await(delay(1))),
]));
return "Hybrid Done";
}),
// Pure fiber-based async — no process spawn at all
async(fn() => await(delay(1))),
])->wait();
$pool->shutdown();
$duration = microtime(true) - $start;
echo "Executed ~5 seconds of work in: {$duration} seconds!";
// Output: Executed ~5 seconds of work in: 1.04 seconds!
use function Hibla\{parallel, await};
try {
await(parallel(function () {
throw new \BadFunctionCallException("Database connection failed!");
}));
} catch (\BadFunctionCallException $e) {
echo $e->getMessage(); // "Database connection failed!"
echo $e->getTraceAsString();
/*
#0 ParentCode.php: Line where parallel() was called
#1 --- WORKER STACK TRACE ---
#2 worker.php: Line where exception was thrown
*/
}
use Hibla\Parallel\Exceptions\ProcessCrashedException;
use function Hibla\{parallel, await};
try {
await(parallel(fn() => exit(1)));
} catch (ProcessCrashedException $e) {
echo "Alert: Worker crashed unexpectedly!";
}
use Hibla\Parallel\Parallel;
$pool = Parallel::pool(size: 4);
$promise = $pool->run(fn() => sleep(100));
$promise->cancel();
// 1. Hibla kills the OS process and all its descendants via full tree kill.
// 2. The pool respawns a fresh replacement worker.
// 3. The promise is settled as cancelled.
$pool->shutdown();
$promise = parallel(function () {
// These nested workers are also killed if the parent is cancelled
await(Promise::all([
parallel(fn() => writeToDatabase()),
parallel(fn() => writeToDatabase()),
]));
});
$promise->cancel();
// The parent worker AND both nested workers are all terminated.
// Neither database write completes — cancellation is a hard guarantee.
use Hibla\Parallel\Exceptions\{
ParallelException,
ProcessCrashedException,
TimeoutException,
};
use function Hibla\{parallel, await};
try {
await(parallel(fn() => riskyWork()));
} catch (TimeoutException $e) {
// Task ran too long
} catch (ProcessCrashedException $e) {
// Worker died mid-task
} catch (ParallelException $e) {
// Any other Hibla error
}
use Hibla\Parallel\Utilities\SystemUtilities;
$cores = SystemUtilities::getCpuCount();
echo $cores; // e.g. 8
use Hibla\Parallel\Parallel;
use Hibla\Parallel\Utilities\SystemUtilities;
$pool = Parallel::pool(size: SystemUtilities::getCpuCount());
use Hibla\Parallel\Utilities\SystemUtilities;
echo SystemUtilities::getPhpBinary(); // e.g. /usr/bin/php8.4
use Hibla\Parallel\Utilities\SystemUtilities;
use Hibla\Parallel\Exceptions\EnvironmentException;
try {
SystemUtilities::validateEnvironment();
} catch (EnvironmentException $e) {
// e.g. "proc_open, shell_exec are disabled in php.ini"
die("Hibla Parallel cannot run: " . $e->getMessage());
}
use Hibla\Parallel\Parallel;
use function Hibla\await;
$result = await(Parallel::task()->run(fn() => "Facade result"));
use Hibla\Parallel\ProcessPool;
$pool = new ProcessPool(size: 8);
$pool->run(fn() => "Direct instantiation result");
$pool->shutdown();
use Hibla\Parallel\Interfaces\ParallelExecutorInterface;
class ReportGenerator
{
public function __construct(
private ParallelExecutorInterface $executor
) {}
public function generate(array $data): mixed
{
return $this->executor->run(fn() => $this->heavyLogic($data));
}
}
// In production
$generator = new ReportGenerator(Parallel::pool(4));
// In tests
$mock = Mockery::mock(ParallelExecutorInterface::class);
$mock->shouldReceive('run')->andReturn(Promise::resolved('mock_data'));
$generator = new ReportGenerator($mock);