Multithreaded PHP
About
Actually this is not real multi-threading, but does forking instead. With this you are able to make simultaneous multiple remote calls while executing just one PHP file.
This is especially usefully e.g. if you have to retrieve more than one XML for preparing the user data or if the remote server just takes too long for one request to response and you’re going to batch process some requests.
The class uses an sqlite-database for holding request data.
Example
require_once(‘lib/class.Forker.php’);<br><br>$fruits = array(<br>‘Apple’, ‘Apricot’, ‘Avocado’, ‘Breadfruit’, ‘Banana’, ‘Blackberry’, ‘Blackcurrant’,<br>‘Blueberry’, ‘Cherimoya’, ‘Cherry’, ‘Clementine’, ‘Coconut’, ‘Cranberry’, ‘Custard’,<br>‘Durian’, ‘Fig’, ‘Grapefruit’, ‘Grape’, ‘Guava’, ‘Jakfruit’, ‘Kiwi’, ‘Lemon’,<br>‘Lime’, ‘Loganberry’, ‘Mandarin’, ‘Mango’, ‘Mangosteen’, ‘Melon’, ‘Nectarine’,<br>‘Orange’, ‘Papaya’, ‘Peach’, ‘Pear’, ‘Persimmon’, ‘Pinapple’, ‘Plum’, ‘Pomegranate’,<br>‘Quince’, ‘Satsuma’, ‘Sharon’, ‘Strawberry’, ‘Tamarillo’, ‘Ugli’, ‘Watermelon’,<br>);<br><br>/**<br>* Main fork handler<br>* @return array<br>*/<br>function forkHandler($queue, $param)<br>{<br>echo "PID {$param['pid']}: getting {$queue['fruit']}.\n";<br>sleep(rand(1,5));<br>echo "PID {$param['pid']}: done.\n";<br>return $arr;<br>}<br><br>$forker = new Forker();<br><br>// add some jobs<br>foreach ($fruits as $fruit) {<br>$jobQuery = Array(‘fruit’=>$fruit);<br>$forker->addQuery($jobQuery);<br>}<br><br>$forker->setForkHandler(‘forkHandler’);<br>$forker->setMaxChildren(20);<br>$forker->startQueue();