simple parallel processing class
Posted: Sat Aug 07, 2010 11:23 am
Here's a little parallel processing script I made. You can start as many processes and either just let them do there thing, or wait until they are all done before proceeding. Let me know what you think.
It can be used as so:
This will generate the header and left blocks simultaneously and then wait for them both to be finished before proceeding.
edit: added $params parameter to dispatch in order to pass variables in. Now you can pass variables into the new thread by sticking them into an array and passing them in together. The only problem I'm having with this class is that you can't get data out of the child thread back to the parent thread, from what I've read you can't do that with fork. But I feel there has to be some way.
Shawn
Code: Select all
<?php
/*
* Run parallel process
*/
class Dispatcher
{
// number of processes running
var $threads;
function __construct()
{
$this->threads = 0;
}
// dispatch a new thread
function dispatch($file , &$params = null)
{
$this->threads++;
// start new thread
$pid = pcntl_fork();
if($pid == -1) // fork failed
{
return false;
}
elseif ($pid > 0) // parent
{
return true;
}
else // child
{
// include requested file
include($file);
exit;
}
}
// wait for all threads to finish
function wait(&$status = null)
{
//wait for each thread to finish
for ($i=0; $i < $this->threads; $i++)
{
pcntl_wait($status);
}
}
}
?>
Code: Select all
$async = new Dispatcher();
$async->dispatch("blocks/header.php");
$async->dispatch("blocks/left.php");
$async->wait();
edit: added $params parameter to dispatch in order to pass variables in. Now you can pass variables into the new thread by sticking them into an array and passing them in together. The only problem I'm having with this class is that you can't get data out of the child thread back to the parent thread, from what I've read you can't do that with fork. But I feel there has to be some way.
Shawn