Created
August 15, 2022 07:55
-
-
Save alexander-zierhut/fe0553dad1914320c7fdb90810c399b6 to your computer and use it in GitHub Desktop.
Example usage of pcntl_fork
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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