Skip to content

Instantly share code, notes, and snippets.

@yendor
Created November 14, 2011 05:54
Show Gist options
  • Save yendor/1363349 to your computer and use it in GitHub Desktop.
Save yendor/1363349 to your computer and use it in GitHub Desktop.
Base class for doing forked, parallel execution in PHP easily
<?php
class ParallelTask
{
protected $pid = null;
public $max_workers = 8;
protected $num_workers = 0;
public function run()
{
$items = $this->get_data();
foreach ($items as $item) {
while ($this->num_workers < $this->max_workers) {
$pid = pcntl_fork();
// Error
if ($pid == -1) {
die('could not fork');
}
// Worker
elseif ($pid === 0) {
if ($this->do_work($item)) {
exit(0);
}
else {
exit(1);
}
}
// Parent
else {
$this->num_workers++;
}
}
// Wait until a child exits before trying to do more work
pcntl_wait($status); //Protect against Zombie children
$this->num_workers--;
}
}
protected function do_work($id)
{
return true;
}
protected function get_data()
{
return array();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment