4

I am building a large php framework. Now we are trying to utilise the all possible cores in each script.

How can be run one script across multiple cores. For example lets say I have two functions on one php file which do hefty processing. How can I run both at the same time on two different processors and then return the results to the script and continue with the rest of the processing.

Are there any other scripts that can be used to create web applications like this...I have tried looking on-line but only solutions I have found were in desktop applications

Anush
  • 1,040
  • 2
  • 11
  • 26
  • If you have many clients you probably already utilizing the cores. What you could *maybe* gain is a bit faster response... does it worth it? what does `mpstat` show? – Karoly Horvath Jul 29 '11 at 23:22

3 Answers3

1

You want to look into PCNTL. Keep in mind it's designed for the CGI-mod but it can be used for apache.

Example usage:

<?php 
// Create the MySQL connection 
$db = mysql_connect($server, $username, $password); 

$pid = pcntl_fork(); 

if ( $pid == -1 ) {        
    // Fork failed            
    exit(1); 
} else if ( $pid ) { 
    // We are the parent 
    // Can no longer use $db because it will be closed by the child 
    // Instead, make a new MySQL connection for ourselves to work with 
    $db = mysql_connect($server, $username, $password, true); 
} else { 
    // We are the child 
    // Do something with the inherited connection here 
    // It will get closed upon exit 
    exit(0); 
?> 
AlienWebguy
  • 76,997
  • 17
  • 122
  • 145
  • that would be great for the child process but what i wanna run two functions simultaneously... – Anush Jul 29 '11 at 23:24
  • Well forking makes a clone of the process, so you can do with it whatever you need. The PCNTL is the requirement, regardless and pcntl_fork() is what you want. This example was just an example :) – AlienWebguy Jul 29 '11 at 23:28
  • but wouldn't making a clone be expensive and also how would you determine which function is which. – Anush Jul 29 '11 at 23:34
  • Yes it's potentially expensive depending on when you make the clone. You determine which clone is which based off the `pid`. You could always make a batch script to spawn new processes from the command line too. – AlienWebguy Jul 29 '11 at 23:38
1

There is no such multiprocessing method. What you may do is create a main php file and then have a file that does something and then make multiple ajax calls to that to open multiple threads for it. Thats what I do. easy and not too complex to setup

Vish
  • 4,508
  • 10
  • 42
  • 74
0

you cant use threads in php. this older posts might be useful, though:

so i guess you will need to fork and synchronize via any of the ipc options, so this also older post might be helpful: How to IPC between PHP clients and a C Daemon Server?

Community
  • 1
  • 1
marcelog
  • 7,062
  • 1
  • 33
  • 46