Skip to content

Instantly share code, notes, and snippets.

@turanct
Created August 27, 2014 17:35
Show Gist options
  • Save turanct/1f98b91045a6bf41a0a7 to your computer and use it in GitHub Desktop.
Save turanct/1f98b91045a6bf41a0a7 to your computer and use it in GitHub Desktop.
Simple forking for executing tasks
<?php
class CouldNotForkException extends Exception {}
class Fork
{
private $task;
public function __construct(Closure $task)
{
$this->task = $task;
}
public function run()
{
// @todo check if pcntl_fork() exists and throw appropriate exception
$pid = pcntl_fork();
if ($pid == -1) {
throw new CouldNotForkException('Received erronious pid.');
} elseif ($pid) {
// Parent process
// Noop
} else {
// Child process
// Execute the task
$task = $this->task;
$task();
exit;
}
}
public function wait()
{
pcntl_wait($status);
}
}
/**
* This function will generate simple tasks that consist of a random wait time, and an echo call
*
* @param mixed $id The id for the task
*/
function getTask($id)
{
return function() use ($id) {
$time = rand(1, 10);
sleep($time);
echo $id;
};
}
// Create a list of a few tasks that we want to run simultaniously
$tasks = array();
$tasks[] = getTask(1);
$tasks[] = getTask(2);
$tasks[] = getTask(3);
// Create forks for each task, and run them
$forks = array();
foreach ($tasks as $task) {
$fork = new Fork($task);
$fork->run();
$forks[] = $fork;
}
// Wait for running tasks, before proceeding
foreach ($forks as $fork) {
$fork->wait();
}
echo 'done';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment