最近工作需要,需要为商户发送weixin的消息模板,而消息模板是通过curl请求的http api,单进程发送太慢,多开脚本又无法系统化、脚本数量无法精确化,系统资源占用高,于是想起采用多线程。
看了张宴的博客,很不错,原文地址:http://zyan.cc/pthreads/
pthread的安装就不赘述了,下载进行动态加载或者静态编译均可: http://php.net/manual/zh/book.pthreads.php
下面是我测试的脚本:
1<?php 2class TestThread extends Thread 3{ 4 public $url ; 5 public $data ; 6 public function __construct($url) 7 { 8 $this->url = $url ; 9 } 10 public function run() 11 { 12 $this->data = curlGet($this->url) ; 13 } 14} 15function curlGet($url) 16{ 17 // 创建一个新cURL资源 18 $ch = curl_init(); 19 // 设置URL和相应的选项 20 curl_setopt($ch, CURLOPT_URL, $url); 21 curl_setopt($ch, CURLOPT_HEADER, 0); 22 curl_setopt($ch, CURLOPT_TIMEOUT, 5) ; 23 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1) ; 24 // 抓取URL并把它传递给浏览器 25 $data = curl_exec($ch); 26 // 关闭cURL资源,并且释放系统资源 27 curl_close($ch); 28 return $data ; 29} 30function createThread($urlArray) 31{ 32 //create thread 33 foreach ($urlArray as $i=>$url) { 34 $threadArray[$i] = new TestThread($url) ; 35 $threadArray[$i]->start() ; 36 } 37 foreach ($threadArray as $key => $thread) { 38 while($thread->isRunning()){ 39 usleep(10) ; 40 } 41 if($thread->join()){ 42 $threadDataArray[$key] = $thread->data."==".$key."\n" ; 43 } 44 } 45 return $threadDataArray ; 46} 47for($i=0; $i<100; $i++){ 48 $url = 'http://baidu.com' ; 49 $urlArray[] = $url ; 50} 51$t = microtime(true); 52$data = createThread($urlArray); 53$e = microtime(true); 54echo "多线程:".($e-$t)."\n"; 55$t = microtime(true); 56for($j=0; $j<20; $j++){ 57 $tmpUrlArray = array_slice($urlArray,0,5) ; 58 $data = createThread($tmpUrlArray); 59} 60$e = microtime(true); 61echo "多线程2:".($e-$t)."\n"; 62$t = microtime(true); 63foreach ($urlArray as $key => $value) 64{ 65 $result_new[$key] = curlGet($value); 66} 67$e = microtime(true); 68echo "For循环:".($e-$t)."\n"; 69?>
测试环境:Dell 2950 2GRAM
测试结果:
多线程:0.44615602493286
多线程2:0.50709319114685
For循环:1.3469228744507
线程太多不仅瞬间占用CPU和内存过高,耗时最小;单进程curl明显是耗时最长的;第二种多线程则是在资源占用和耗时上趋于中间的,所以在实际的线上环境明显要采用这种的。