PHP Developers Network

A community of PHP developers offering assistance, advice, discussion, and friendship.
 
Loading
It is currently Mon Nov 18, 2019 10:57 pm

All times are UTC - 5 hours




Post new topic Reply to topic  [ 1 post ] 
Author Message
PostPosted: Sat Aug 07, 2010 11:23 am 
Offline
Forum Contributor

Joined: Mon Apr 05, 2010 3:38 pm
Posts: 212
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.

Syntax: [ Download ] [ Hide ]
<?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:
Syntax: [ Download ] [ Hide ]
$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


Top
 Profile  
 
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 1 post ] 

All times are UTC - 5 hours


Who is online

Users browsing this forum: No registered users and 1 guest


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  
cron
Powered by phpBB® Forum Software © phpBB Group