Skip to content

Instantly share code, notes, and snippets.

@alexander-zierhut
Created August 15, 2022 07:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexander-zierhut/fe0553dad1914320c7fdb90810c399b6 to your computer and use it in GitHub Desktop.
Save alexander-zierhut/fe0553dad1914320c7fdb90810c399b6 to your computer and use it in GitHub Desktop.
Example usage of pcntl_fork
<?php
class Task {
private $cb;
public function __construct(callable $cb) {
$this->cb = $cb;
}
public function start() {
$pid = pcntl_fork();
if ($pid == -1) {
die('could not fork');
} else if ($pid) {
return;
pcntl_wait($status); //Protect against Zombie children
} else {
($this->cb)();
exit;
}
}
}
$task1 = new Task(function() {
for($i = 0; $i <= 100; $i++) {
echo "\n1: Task: $i";
usleep(10000);
}
});
$task2 = new Task(function() {
for($i = 0; $i <= 100; $i++) {
echo "\n2: Task: $i";
usleep(20000);
}
});
$task1->start();
$task2->start();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment