simple parallel processing class

Coding Critique is the place to post source code for peer review by other members of DevNetwork. Any kind of code can be posted. Code posted does not have to be limited to PHP. All members are invited to contribute constructive criticism with the goal of improving the code. Posted code should include some background information about it and what areas you specifically would like help with.

Popular code excerpts may be moved to "Code Snippets" by the moderators.

Moderator: General Moderators

Post Reply
shawngoldw
Forum Contributor
Posts: 212
Joined: Mon Apr 05, 2010 3:38 pm

simple parallel processing class

Post by shawngoldw »

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.

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);
		}
	}
}


?>
It can be used as so:

Code: Select all

$async = new Dispatcher();
$async->dispatch("blocks/header.php");
$async->dispatch("blocks/left.php");
$async->wait();
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
Post Reply