<?php
class AsyncOperation extends Thread {
public function __construct($arg){
$this->arg = $arg;
}
public function run(){
if($this->arg){
printf("Hello %s\n", $this->arg);
}
}
}
$thread = new AsyncOperation("World");
if($thread->start())
$thread->join();
?>
实现异步执行POST操作
<?php
$t1 = microtime(true);
class AsyncPost extends \Thread {
public function __construct($url,$post,$index){
$this->url = $url;
$this->post = $post;
$this->index = $index;
}
public function run(){
if(!empty($this->url)){
return $this->post($this->url,$this->post,$this->index);
}
}
public function Post($url, $post = null,$index)
{
$post_data = $post;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// post数据
curl_setopt($ch, CURLOPT_POST, 1);
// post的变量
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$output = curl_exec($ch);
curl_close($ch);
//打印获得的数据
echo intval($index)."\r\n";
return $output;
}
}
echo "NUL"."\r\n";
$workers = [];
for($i=0;$i<10;$i++){
$workers[$i] = new AsyncPost('http://www.0-php.com', "www.0-php.com",$i);
$workers[$i]->start();//创建多线程
}
foreach ($workers as $key=>$worker) {
while($workers[$key]->isRunning()) {
usleep(100);
}
if ($workers[$key]->join()) {//启动多线程
print_r($workers[$key]->result);
}
}
$t2 = microtime(true);
echo '耗时'.round($t2-$t1,3).'秒';
输出结果:
D:\www.0-php.com>php index.php
扤UL
0
1
2
3
4
5
6
7
8
9