Multithreading in PHP
by Raja[ Edit ] 2008-02-11 16:34:14
It is basically a workaround for doing a functionality similar to threading. ie., it doesn't include all the aspects of threading concept.
Threading is defined as executing different parts of a same program in a time-shared manner.
But, here different programs are executed parallelly ie., They are instantiated to run one by one from the main program in the background. The status of every program is tracked in Database(whether they are being executed or not) and is constantly checked. And when a particular program has ended its execution it is re-run.
A single program can be instantiated many times instead of several programs so that a single program can be run more than once in the background(possibly with different arguments).
Here I explain executing a single program as several threads in the background.
A mysql table called statustable has five fields each representing a thread's status as 0 or 1 and has only one row. ex., t1sta, t2sta,..,t5sta are the fields and initially the values of the only one row available is all set to 0's.
Main.php
...
...
for($i=0;$i<100;$i++)
{
while(true)
{
$j=0;
$result1 = mysql_query("select * from statustable");
$inuse = mysql_fetch_row($result1);
for(;$j<5;$j++)
{
if(!$inuse[$j])
{
$thread= "t".($j+1)."sta";
mysql_query("update statustable set $thread=1" );
exec("php /home/uname/public_html/testing/thread.php $j > /dev/null 2>&1 &");
break 2;
}
}
}
}
....
....
thread.php
<?php
$threadno = $argv[1];
$thread= "t".($threadno+1)."sta"; // the $thread will have values like t1sta, t2sta,etc
....
....
// Other argument like $argv[2],etc can be used as arguments for this file
....
....
mysql_query("update statustable set $thread=0"); //at the end of the program set status
?>
Here thread.php is executed 100 times with 5 threads running in the background at a time.