Multithreading in PHP with pcntl Functions

By | April 27, 2008

Sometimes you need to run several copies of one script at the same time. The easiest method is to do something like this:

for($i=0;$i<10;$i++)
{
system ("/usr/local/bin/php go.php $i > start.log &");
echo "thread $i started";
}
?>

Not very elegant, but it works, if you are allowed to use PHP’s system() function. I will tell you how to use pcntl function for this task. Coding is quite simple too:

for ($k=1; $k<=$children; $k++)
{

$pid = pcntl_fork();
if ($pid == -1)
{
die(“could not forkn”);
}
else if ($pid)
{
exit(0);
}
else
{
$cpid = pcntl_fork();
if ($cpid == -1)
{
die(“could not fork in child processn”);
}
if (!$cpid)
{
// Do anything you need here
}
}
}
You should have PHP compiled with pcntl support. pcntl extention does not work in Windows environment, so this method is usable on LAMP systems only. It allows true multithreading in PHP