Skip to content

Instantly share code, notes, and snippets.

@jensscherbl
Last active June 3, 2026 13:00
Show Gist options
  • Select an option

  • Save jensscherbl/fba47d61356e3f2e4e4bd9b39efa88c4 to your computer and use it in GitHub Desktop.

Select an option

Save jensscherbl/fba47d61356e3f2e4e4bd9b39efa88c4 to your computer and use it in GitHub Desktop.
<?php
final class Worker
{
private $id;
private $handle;
private $mutex;
private $condition;
private $loop;
private $callables;
public function __construct()
{
$this->mutex = fhread_mutex_init();
$this->condition = fhread_cond_init();
$this->loop = true;
$this->callables = [];
}
public function __destruct()
{
fhread_cond_destroy(
$this->condition
);
fhread_mutex_destroy(
$this->mutex
);
}
public function start()
{
fhread_create(
$this,
$this->id,
$this->handle
);
}
public function run()
{
do {
fhread_mutex_lock(
$this->mutex
);
if (count($this->callables) === 0) {
fhread_cond_wait(
$this->condition,
$this->mutex
);
}
$callable = array_shift(
$this->callables
);
fhread_mutex_unlock(
$this->mutex
);
$callable();
} while ($this->loop);
}
public function assign(callable $callable)
{
fhread_mutex_lock(
$this->mutex
);
$this->callables[] = $callable;
fhread_mutex_unlock(
$this->mutex
);
fhread_cond_signal(
$this->condition
);
}
public function join()
{
$error = null;
$this->assign(function () {
$this->loop = false;
});
fhread_join(
$this->handle,
$error
);
}
}
$worker = new Worker;
$worker->start();
$worker->assign(function () { echo 'Task 1.' . PHP_EOL; });
$worker->assign(function () { echo 'Task 2.' . PHP_EOL; });
$worker->assign(function () { echo 'Task 3.' . PHP_EOL; });
$worker->assign(function () { echo 'Task 4.' . PHP_EOL; });
$worker->assign(function () { echo 'Task 5.' . PHP_EOL; });
$worker->join();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment