Jump to content

Write PHP That Uses All 4 CPUS To Process :: Multithreaded


JustinK101

Recommended Posts

I need to write a PHP application, that will run via the command line:

 

php -f /home/justin/process_data.php

 

The server I am running it on has 4 CPU cores, and the processing I am doing is intense, and I want it to run as quick as possible. It is my understanding that php is single threaded, i.e. when executing PHP scripts it only uses a single processor, unless you tell is otherwise. Can anybody provide code to create 4 threads, and utilize all 4 CPUs?

 

PSEUDOCODE

//assume 4 arrays of data to process
$data_1 = array();
$data_2 = array();
$data_3 = array();
$data_4 = array();

//thread1
process($data_1);

//thread2
process($data_2);

//thread3
process($data_3);

//thread4
process($data_4);

 

Thorpe,

 

Ok, seems that pcntl_fork() is what I need, but a bit confused on how to use it. Here is from the doc how to fork two processes. How is this modified to fork four processes? Thanks.

 

$pid = pcntl_fork();
if ($pid == -1) {
     die('could not fork');
} else if ($pid) {
     // we are the parent
     pcntl_wait($status); //Protect against Zombie children
} else {
     // we are the child
}

Actually, think I got it, but if you see an errors [thorpe] could you let me know. This is my example. You should see four PHP processes running, when executing this. Also, you should see all four CPUS using close to 100% cpu.

 

<?php
$pid_1 = pcntl_fork();

if($pid_1 == -1) {
	trigger_error("Could not fork process", E_USER_ERROR());
} else if($pid_1) {
	$pid_2 = pcntl_fork();

	if($pid_2 == -1) {
		trigger_error("Cloud not fork process", E_USER_ERROR());
	} else if($pid_2) {
		for($i = 0; $i < 9999999999; $i++) {
                        	echo "Running Process [1]...\n";
               		}

		pcntl_wait($status_2);
	} else {
		for($j = 0; $j < 9999999999; $j++) {
                                echo "Running Process [2]...\n";
                 	 }
	}

	pcntl_wait($status_1);
} else {
	$pid_3 = pcntl_fork();

                if($pid_3 == -1) { 
                        trigger_error("Cloud not fork process",	E_USER_ERROR());
	 	} else if($pid_3) {
                        for($k = 0; $k < 9999999999; $k++) {
                                echo "Running Process [3]...\n";
                 	 }

                        pcntl_wait($status_3);
                } else {
                        for($l = 0; $l < 9999999999; $l++) {
                                echo "Running Process [4]...\n";
                         }
	 	}

                pcntl_wait($status_4);
}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.