usage
This commit is contained in:
parent
17ab29ce00
commit
417a2d4d0b
49
example1.php
Normal file
49
example1.php
Normal file
|
@ -0,0 +1,49 @@
|
|||
<?php /*
|
||||
|
||||
Basic usage
|
||||
|
||||
for beginners: it is for command-line only execution. Webservers do not support threads.
|
||||
|
||||
*/
|
||||
|
||||
require_once("ThreadQueue.php");
|
||||
|
||||
|
||||
|
||||
|
||||
// it is the function that will be called several times
|
||||
|
||||
function parallel_task($arg){
|
||||
echo "task with parameter '$arg' starts\n";
|
||||
sleep( rand(2,5) ); // wait for random seconds
|
||||
echo "task with parameter '$arg' ENDS\n";
|
||||
}
|
||||
|
||||
|
||||
|
||||
// create a queue instance with a callable function name
|
||||
$TQ = new ThreadQueue("parallel_task");
|
||||
|
||||
|
||||
// add tasks
|
||||
$TQ->add("one");
|
||||
$TQ->add("two");
|
||||
$TQ->add("three");
|
||||
$TQ->add("four");
|
||||
$TQ->add("five");
|
||||
|
||||
|
||||
|
||||
|
||||
// wait until all threads exit
|
||||
|
||||
while( count( $TQ->threads() ) ){ // there are existing processes in the background?
|
||||
sleep(1); // optional
|
||||
|
||||
echo "waiting for all jobs done...\n";
|
||||
$TQ->tick(); // mandatory!
|
||||
|
||||
}
|
||||
|
||||
echo "all process finished.\n";
|
||||
|
64
example2.php
Normal file
64
example2.php
Normal file
|
@ -0,0 +1,64 @@
|
|||
<?php /*
|
||||
|
||||
Advanced usage
|
||||
|
||||
*/
|
||||
|
||||
require_once("ThreadQueue.php");
|
||||
|
||||
|
||||
|
||||
|
||||
// it is the function that will be called several times
|
||||
|
||||
function parallel_task($arg){
|
||||
echo "task with parameter '$arg' starts\n";
|
||||
sleep( rand(2,5) ); // wait for random seconds
|
||||
echo "task with parameter '$arg' ENDS\n";
|
||||
}
|
||||
|
||||
|
||||
|
||||
// we want 3 jobs in parallel instead of the default 2
|
||||
$TQ = new ThreadQueue("parallel_task", 3);
|
||||
|
||||
|
||||
// add tasks
|
||||
$TQ->add("one");
|
||||
$TQ->add("two");
|
||||
$TQ->add("three");
|
||||
$TQ->add("four");
|
||||
$TQ->add("five");
|
||||
$TQ->add("six");
|
||||
|
||||
// Oops! We changed our mind, let's remove awaiting jobs.
|
||||
// Existing threads will run, but jobs not started will be removed.
|
||||
$TQ->flush();
|
||||
|
||||
|
||||
// let's add jobs again.
|
||||
$TQ->add("seven");
|
||||
$TQ->add("eight");
|
||||
$TQ->add("nine");
|
||||
$TQ->add("ten");
|
||||
$TQ->add("eleven");
|
||||
$TQ->add("twelve");
|
||||
|
||||
|
||||
|
||||
|
||||
// wait until all threads exit
|
||||
|
||||
while( $numberOfThreads = count($TQ->threads()) ){
|
||||
usleep(500000); // optional
|
||||
|
||||
echo "waiting for all ($numberOfThreads) jobs done...\n";
|
||||
$TQ->tick(); // mandatory!
|
||||
|
||||
// ha-ha! we can change the number of parallel executions realtime.
|
||||
$TQ->queueSize = 4;
|
||||
|
||||
}
|
||||
|
||||
echo "all process finished.\n";
|
||||
|
Loading…
Reference in a new issue