84669 Lernen von Personen
152542 Lernen von Personen
20005 Lernen von Personen
5487 Lernen von Personen
7821 Lernen von Personen
359900 Lernen von Personen
3350 Lernen von Personen
180660 Lernen von Personen
48569 Lernen von Personen
18603 Lernen von Personen
40936 Lernen von Personen
1549 Lernen von Personen
1183 Lernen von Personen
32909 Lernen von Personen
大家简单聊一下php多线程的应用场合吧,例如php的pthreads,哪些业务操作需要用多线程?
认证高级PHP讲师
http://pecl.php.net/package/pthreads 下载tgz包,里面提供有众多examples示例代码,最简单的就是开启多个线程采集网络资源:
<?php class Request extends Thread { public $url; public $data; public function __construct($url) { $this->url = $url; } public function run() { // 线程处理一个耗时5秒的任务 for($i=0;$i<5;$i++) { echo '线程: '.date('H:i:s')."\n"; sleep(1); } $response = file_get_contents($this->url); if ($response) { $this->data = array($response); } echo "线程: 任务完成\n"; } } $request = new Request('hello.html'); // 运行线程:start()方法会触发run()运行 if ($request->start()) { // 主进程处理一个耗时10秒的任务,此时线程已经工作 for($i=0;$i<10;$i++) { echo '进程: '.date('H:i:s')."\n"; sleep(1); } // 同步线程并输出线程返回的数据 $request->join(); echo '线程返回数据: '.$request->data[0]; } /* 如果顺序执行,合计时间将是15秒,借助线程,则只需10秒. 生成文件: echo 'Hello' > hello.html 运行计时: time php req.php 查看线程: ps -efL|head -n1 && ps -efL|grep php */
值得注意的是,不要在线程里使用echo输出内容,否则会出现不可预知的错误和行为,比如乱码(garbled).尤其是在非CLI环境下,比如Apache/PHP-FPM.
php就不要谈多线程了吧,哈哈
我也想知道.........................
http://pecl.php.net/package/pthreads
下载tgz包,里面提供有众多examples示例代码,最简单的就是开启多个线程采集网络资源:
值得注意的是,不要在线程里使用echo输出内容,否则会出现不可预知的错误和行为,比如乱码(garbled).尤其是在非CLI环境下,比如Apache/PHP-FPM.
php就不要谈多线程了吧,哈哈
我也想知道.........................