-
-
Save fhferreira/8661745 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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