Maison > Article > développement back-end > pthreads多线程数据采集_PHP教程
以前使用curl的多线程并不是真正的多线程,只是一种模拟的多线程,现在使用pthreads来实现真正意义上的多线程。
下载:
windows下:
http://windows.php.net/downloads/pecl/releases/pthreads/0.0.45/
mac、unix、linux下:
https://github.com/krakjoe/pthreads
windows下:
解压得到pthreadVC2.dll和php_pthreads.dll文件,把vc2文件放到php.exe同级目录,把php_pthreads.dll放到扩展目录下。
修改php.ini文件 添加extension=php_pthreads.dll
修改Apache配置文件httpd.conf 添加LoadFile "yourpath/php/pthreadVC2.dll"
mac、unix、linux下:
具体可参考宴哥的博客http://blog.s135.com/pthreads/
调用方式:
具体的用法也可以参考宴哥的博客http://blog.s135.com/pthreads/
结合以前的get_html也可以这样来实现类
<span 1</span> <span class</span> threads <span extends</span><span Thread </span><span 2</span> <span { </span><span 3</span> <span public</span> <span $url</span> = ''<span ; </span><span 4</span> <span public</span> <span $options</span> = <span array</span><span (); </span><span 5</span> <span public</span> <span $data</span><span ; </span><span 6</span> <span 7</span> <span public</span> <span function</span> __construct(<span $url</span>, <span $options</span> = <span array</span><span ()){ </span><span 8</span> <span $this</span>->url = <span $url</span><span ; </span><span 9</span> <span $this</span>->options = <span $options</span><span ; </span><span 10</span> <span } </span><span 11</span> <span 12</span> <span public</span> <span function</span><span run(){ </span><span 13</span> <span if</span>(!<span empty</span>(<span $this</span>-><span url)){ </span><span 14</span> <span $this</span>->data = <span $this</span>->get_html(<span $this</span>->url, <span $this</span>-><span options); </span><span 15</span> <span } </span><span 16</span> <span } </span><span 17</span> <span 18</span> <span public</span> <span function</span> get_html(<span $url</span>,<span $options</span> = <span array</span><span ()){ </span><span 19</span> <span if</span>(<span empty</span>(<span $options</span><span )){ </span><span 20</span> <span $options</span>[CURLOPT_RETURNTRANSFER] = <span true</span><span ; </span><span 21</span> <span $options</span>[CURLOPT_TIMEOUT] = 5<span ; </span><span 22</span> <span } </span><span 23</span> <span $ch</span> = curl_init(<span $url</span><span ); </span><span 24</span> curl_setopt_array(<span $ch</span>,<span $options</span><span ); </span><span 25</span> <span $html</span> = curl_exec(<span $ch</span><span ); </span><span 26</span> curl_close(<span $ch</span><span ); </span><span 27</span> <span if</span>(<span $html</span> === <span false</span><span ){ </span><span 28</span> <span return</span> <span false</span><span ; </span><span 29</span> <span } </span><span 30</span> <span return</span> <span $html</span><span ; </span><span 31</span> <span } </span><span 32</span> }