Skip to content

Instantly share code, notes, and snippets.

@kikoseijo
Forked from kamermans/pthreads_example.php
Created August 30, 2016 14:07
Show Gist options
  • Save kikoseijo/2deec504bb6aa08f1a430c2b2afdfe0c to your computer and use it in GitHub Desktop.
Save kikoseijo/2deec504bb6aa08f1a430c2b2afdfe0c to your computer and use it in GitHub Desktop.
An adaptation of an example from the pthreads project that shows how to make 32 simultaneous web requests in PHP using multi-threading via pthreads.
<?php
error_reporting(E_ALL);
class AsyncWebRequest extends Thread {
public $url;
public $num;
public $data;
public function __construct($url, $num){
$this->url = $url;
$this->num = $num;
}
public function run(){
echo "Thread {$this->num} running\n";
if (($url = $this->url)) {
/*
* If a large amount of data is being requested, you might want to
* fsockopen and read using usleep in between reads
*/
$this->data = file_get_contents($url);
} else printf("Thread #%lu was not provided a URL\n", $this->getThreadId());
}
}
$clock_start = microtime(true);
$threads = [];
for ($i=0; $i<32; $i++) {
$url = sprintf("http://www.google.com/?q=%s", rand()*10);
$mythread = [
'start' => microtime(true),
'thread' => new AsyncWebRequest($url, $i),
'num' => $i,
];
$threads[] = $mythread;
if ($mythread['thread']->start()) {
printf("Thread $i took %f seconds to start\n", microtime(true)-$mythread['start']);
} else {
throw new Exception("Unable to start thread!");
}
}
$work_time = 0;
$running_threads = count($threads);
while ($running_threads > 0) {
foreach ($threads as $idx => $thread) {
if (!$thread['thread']->isRunning()) {
$running_threads--;
// Remove thread from stack
unset($threads[$idx]);
$time = microtime(true)-$thread['start'];
$work_time += $time;
if ($thread['thread']->join()) {
printf("Thread {$thread['thread']->num} took $time seconds to finish receiving %d bytes\n", strlen($thread['thread']->data));
} else {
echo "Thread {$thread['thread']->num} took $time seconds to finish, request failed\n";
}
}
}
}
$clock_time = microtime(true) - $clock_start;
echo "Finished in $clock_time seconds with $work_time CPU seconds\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment