PHP协程使用场景

 1 <?php
 2 class Test {
 3     public function async() {
 4          
 5         $start = microtime(true);
 6         $url = "http://waimai.baidu.com/waimai?qt=poisug";  //随意的一个接口
 7         $i = 50; //假设请求N次
 8         $new_ids = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
 9         foreach ($new_ids as $new_id) {
10             $gen[$new_id] = $this->_request("{$url}&news_id={$new_id}");
11             //实际应用中可能在多次请求之间有其他事情要处理,否则我们可以直接使用curl_multi
12             //suppose i can do something here
13         }
14          
15         $ret = $this->_dealGen($gen);
16         var_dump($ret);
17         $end = microtime(true);
18         echo $end - $start;
19          
20     }
21        
22     protected function _request($url) {
23          
24         $mh = curl_multi_init();       
25         $ch = curl_init();
26         curl_setopt($ch, CURLOPT_URL, $url);      
27         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
28         curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)');
29         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
30         curl_setopt($ch, CURLOPT_MAXREDIRS, 7);
31         curl_multi_add_handle($mh, $ch);
32         do {
33             $mrc = curl_multi_exec($mh, $active);
34             //可以看到很多参考代码这里是sleep(),其实浪费了程序执行的时间
35             yield null;  //先去请求,不用等待结果
36         } while ($active > 0); 
37          
38         $raw = curl_multi_getcontent($ch);
39         curl_multi_remove_handle($mh, $ch);
40         curl_multi_close($mh);
41         yield $raw;    
42     }
43      
44     protected function _dealGen($gens) {
45               
46         $ret = array();
47         do {
48             $running = false;
49             foreach ($gens as $id => $gen) {              
50                 if ($gen->valid()) {
51                     //有任意没处理完的yield就继续进行处理
52                     $running = true;
53                     $gen->next();
54                     $tmp = $gen->current();
55                     if ($tmp !== null) {
56                         $ret[$id] = $tmp;
57                     }
58                 }
59             }
60         } while ($running);       
61         return $ret;          
62     }
63 }
64 
65 $test = new Test();
66 $test->async();

 

上一篇:Qt中暂停线程的执行


下一篇:1388:家谱(gen)