Example #1
0
}
function progress($ch)
{
    // infinite loop
    for (;;) {
        echo "still downloadin'...\n";
        // the second argument to thread_message_queue_poll is a timeout
        // if it times out, it returns the string (not the constant) PHP_THREAD_POLL_TIMEOUT
        // this function is blocking (it waits until a message is recieved or timeout triggered)
        $var = thread_message_queue_poll($ch, 500);
        if ($var == 'done') {
            return;
        }
    }
}
foreach ($sites as $site) {
    echo "Starting download of {$site}!\n";
    $threads[] = thread_create("get_url_threaded", $site);
}
// communication channel
$ch = thread_message_queue_create();
// progress loop
$progress = thread_create('progress', $ch);
// wait for all threads to finish
foreach ($threads as $thread) {
    thread_join($thread);
}
// tell progress to stop
thread_message_queue_post($ch, 'done');
// we are done!
echo "All downloads done!\n";
Example #2
0
{
    for (;;) {
        // receive the message from $ch
        $a = thread_message_queue_poll($ch);
        // TRIPLE COMPARISION IS IMPORTANT!!!!
        if ($a === 'PHP_THREAD_POLL_STOP') {
            break;
        }
        printf("thread %02d: %02s\n", $i, $a * 2);
    }
    sleep(2);
    printf("thread %02s is done.\n", $i);
}
$ch = thread_message_queue_create();
for ($i = 0; $i < 20; $i++) {
    $rs[] = thread_create('sub', $i, $ch);
}
for ($i = 0; $i < 20; $i++) {
    // send $i to $ch
    thread_message_queue_post($ch, $i);
    usleep(200000);
}
// threads are still waiting for a message. tell them that we are stopping
thread_message_queue_stop($ch);
// after threads recieve the stop message, they break out of the for loop and sleep
echo "Done sending messages. Threads are sleeping for 2 seconds.\n";
foreach ($rs as $val) {
    // thread_join waits for the the thread to finish before continuing
    thread_join($val);
}
echo "All threads are complete.";