Ok most people would think threading in php is dificult or not possible so I whipped up this class for one of my projects in about 10 mins. Enjoy.
Dont use this when loading a page with apache2, it can be done but its not recomended.
Only works on linux at this stage, requires the pcntl extension which is linux only!
PHP:
<?php
class Thread {
private $pid = false;
private $file = false;
private $kill = true;
/*
Usage (callback function): $thread1 = new Thread('function','argument1','argument2');
Usage (static calling class): $thread1 = new Thread(array('class name','function'),'argument1','argument2');
Usage (object calling): $thread1 = new Thread(array($object,'function'),'argument1','argument2');
*/
function Thread(){
$this->file = '/tmp/'.md5(rand().rand().rand()+rand()).md5(rand().rand().rand()+rand()).'.thread';
$pid = pcntl_fork();
if ($pid == -1) {
die('could not fork');
} else if ($pid) {
$this->pid = $pid;
} else {
$ar = func_get_args();
$function = $ar[0];
unset($ar[0]);
$return = call_user_func_array($function,$ar);
file_put_contents($this->file,serialize($return));
if($this->kill) posix_kill(getmypid(),9);
else die();
}
}
/*
Because php wasnt made with multi-threading in mind as soon as a thread closes it does a clean up.
Setting this to true prevents php doing a clean up, ensure you unset any global vars you may have defined
in the CHILD thread.
Ensure this is true (default) if you experience the MySQL "Lost Connection during query" problem
*/
function set_kill($setting){
$this->kill = (bool)$setting;
}
/*
Get the function return result. Returns a object.
$return->result is where you will find any result data
$return->error will be set if an error has occured with the error string
*/
function result($clear=true){
$new = new stdClass();
pcntl_waitpid($this->pid,$status);
if(!file_exists($this->file)){
$new->error = 'function triggered error';
$new->result = null;
return $new;
}
$return = unserialize(file_get_contents($this->file));
$new->result = $return;
if($clear) unlink($this->file);
return $new;
}
}
//Demo
function sleep1($n){
sleep($n);
return $n;
}
$thread1 = new Thread('sleep1',6);
$thread2 = new Thread('sleep1',3);
echo 'Now we wait for the threads to complete their "work": ';
echo $thread1->result()->result.'-'.$thread2->result()->result."\r\n";
?>
Only works on linux at this stage, requires the pcntl extension which is linux only!