How To Make PHP Multi-Threading Flow Instead Of Waiting For Completion
I am using the following CURL Multithreading to add multi-threading to PHP processes:
function multithread_it($url,$threads){
$started=0;
while ($started<$threads){
$ch[$started] = curl_init();
curl_setopt($ch[$started], CURLOPT_URL, $url);
curl_setopt($ch[$started], CURLOPT_HEADER, 0);
curl_setopt($ch[$started], CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch[$started], CURLOPT_RETURNTRANSFER, 0);
$started++;
}
$started=0;
$mh = curl_multi_init();
while ($started<$threads){
curl_multi_add_handle($mh,$ch[$started]);
$started++;
}
开发者_如何学Python $started=0;
$running=null;
do {curl_multi_exec($mh,$running);} while($running > 0);
while ($started<$threads){
curl_multi_remove_handle($mh, $ch[$started]);
$started++;
}
curl_multi_close($mh);
ob_flush();
flush();
}
This is called using, E.g.
multithread_it($script_dir."script.php",10);
Inside of script.php I have:
for($i=0;$i<10;$i++){
echo $i."<br />";
sleep(1);
ob_flush();
flush();
}
But the data stalls. The script that calls multithread_it waits until all scripts have been completed before showing the data which suddenly jumps on the screen.
This is only sample data of a script that actually takes around 10 minutes to run but the very same concept and codes used with flush, ob_flush and the exact function.
Any ideas how I could get the content inside of script.php to show in the parent script as it loads?
Curl is running with multiple threads in downloading multiple urls, but your php code is still single threaded, which means that it will wait for curl to finish before you can act on all of the downloads.
The closest thing PHP has to threading are the process control functions.: http://www.php.net/manual/en/book.pcntl.php
精彩评论