Created
November 14, 2011 05:54
-
-
Save yendor/1363349 to your computer and use it in GitHub Desktop.
Base class for doing forked, parallel execution in PHP easily
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 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