<?php
DECLARE (ticks = 1);
$running = 1;
Signal Processing function
function Sig_handler ($signo)
{
Switch ($signo) {
Case SIGINT:
Finish ();
Break
Default
Break
}
}
Pcntl_signal (SIGINT, "Sig_handler");
Class Test extends \thread {
public $url;
public $result;
Public function __construct ($url) {
$this->url = $url;
}
Public Function run () {
if ($this->url) {
$this->result = model_http_curl_get ($this->url);
}
}
}
function Model_http_curl_get ($url) {
$curl = Curl_init ();
curl_setopt ($curl, Curlopt_url, $url);
curl_setopt ($curl, Curlopt_returntransfer, 1);
curl_setopt ($curl, Curlopt_timeout, 5);
curl_setopt ($curl, Curlopt_useragent, ' mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2);
$result = curl_exec ($curl);
Curl_close ($curl);
return $result;
}
for ($i = 0; $i < $i + +) {
$urls [] = ' http://www.baidu.com/s?wd= '. RAND (10000, 20000);
}
$pool = Array ();
For ($i =1 $i <=5; $i + +) {
$key = Uniqid ();
$url = Array_shift ($urls);
$pool [$key] = new test ($url);
$pool [$key]->start ();
echo "Start thread $key\n";
}
while ($urls && $running) {
foreach ($pool as $key => $worker) {
if (! $worker->isrunning ()) {
Unset ($pool [$key]);
echo "Thread". $key. " Ended \ n ";
$url = Array_shift ($urls);
$pool [$key] = new test ($url);
$pool [$key]->start ();
echo "Start thread $key\n";
}
}
Usleep (1000);
}
function Finish () {
Global $running;
Global $pool;
$running = 0;
echo "Receives the signal, waits for the thread end to run \ n";
foreach ($pool as $key => $worker) {
if ($pool [$key]->join ()) {
Var_dump ($pool [$key]->result);
}
}
}