`

php多线程

    博客分类:
  • php
阅读更多

一直没有找到PHP有像JAVA一样的多线程机制,网上有的也只是使用get&post模拟出来的多线程。今天,偶尔看到PHP 4 >= 4.1.0, PHP 5有这个函数:

 

pcntl_forkForks the currently running process

Description

int pcntl_fork ( void )

The pcntl_fork() function creates a child process that differs from the parent process only in its PID and PPID. Please see your system's fork(2) man page for specific details as to how fork works on your system.

Return Values

On success, the PID of the child process is returned in the parent's thread of execution, and a 0 is returned in the child's thread of execution. On failure, a -1 will be returned in the parent's context, no child process will be created, and a PHP error is raised.

 

<?php

$pid  =  pcntl_fork ();
if ( $pid  == - 1 ) {
     die( 'could not fork' );
} else if ( $pid ) {
      // we are the parent
      pcntl_wait ( $status );  //Protect against Zombie children
} else {
      // we are the child
}

?>
 
貌似会创建一个子线程,不知道在我的板子上好不好用,有空试试。

另外附上有个lady写的,CURL的多线程程序:
Most PHP developers have heard of the CURL extension for PHP or even used it. However it is mostly used in a basic form: to retrieve content from other websites or (RESTful) webservices. Ofcourse PHP itself offers several functions (like fopen or fsockopen) for getting this content, but they are all very basic. It is easy to run into limitations, for example you might want to define the request method or set another user agent (if you're building a webspider). This is where the curl extension kicks in. It is a separate library that has to be compiled with PHP in order to use it. The Curl extension has many functions and options which offer the developer more flexibility than the standard PHP functions.
Let me show you a simple example of using Curl to get the content of another website.

PHP:

<?php

   // create the curl handle
   $ch  =  curl_init ();
  
   // setting several options like url, timeout, returntransfer
   curl_setopt ( $ch ,  CURLOPT_URL ,  'http://www.google.com' );
   curl_setopt ( $ch ,  CURLOPT_TIMEOUT ,  30 );
   curl_setopt ( $ch ,  CURLOPT_RETURNTRANSFER ,  true );
  
   // get the content of the url and put it into the output variable (thanks to the returntransfer option)
   $output  =  curl_exec ( $ch );
  
   // echo the output to the screen
   echo  $output ;
  
   // Print the curl info like http response code, content type etc.
   echo  '<pre>' ;
   print_r  ( curl_getinfo ( $ch ));
  echo  '</pre>' ;
  
   // close the curl handle to free system resources
   curl_close ( $ch );

?>
 



A good tutorial which covers the basics of using curl can be found here .

Besides using curl for getting the content of other websites, it is also possible to use curl for multithreading in PHP. PHP has no native support for multithreading like Java. Each PHP request is a separate thread. There are some workarounds like using pcntl_fork, starting multiple commandline php processes using the exec command or even using ajax. Another possibility is using the Curl library. Besides the basic functions described above Curl offers the "multi" functions for retrieving content from several url's at the same time. Let's take a look at these functions using an example:

PHP:

<?php

   // create the multi curl handle
   $mh  =  curl_multi_init ();
   $handles  = array();
  
  for( $i = 0 ; $i < 5 ; $i ++)
  {
     // create a new single curl handle
     $ch  =  curl_init ();
    
     // setting several options like url, timeout, returntransfer
    // simulate multithreading by calling the wait.php script and sleeping for $rand seconds
     curl_setopt ( $ch ,  CURLOPT_URL ,  "http://put your url here/wait.php?seconds=" .( $i + 1 ));
     curl_setopt ( $ch ,  CURLOPT_HEADER ,  0 );
     curl_setopt ( $ch ,  CURLOPT_RETURNTRANSFER ,  true );
     curl_setopt ( $ch ,  CURLOPT_TIMEOUT ,  30 );
    
     // add this handle to the multi handle
     curl_multi_add_handle ( $mh , $ch );
    
     // put the handles in an array to loop this later on
     $handles [] =  $ch ;
  }
  
   // execute the multi handle
   $running = null ;
  do 
  {
     curl_multi_exec ( $mh , $running );
     // added a usleep for 0.25 seconds to reduce load
     usleep  ( 250000 );
  } while ( $running  >  0 );
  
   // get the content of the urls (if there is any)
   for( $i = 0 ; $i < count ( $handles ); $i ++)
  {
     // get the content of the handle
     $output .=  curl_multi_getcontent ( $handles [ $i ]);
    
     // remove the handle from the multi handle
     curl_multi_remove_handle ( $mh , $handles [ $i ]);
  }
  
   // echo the output to the screen
   echo  $output ;
  
   // close the multi curl handle to free system resources
   curl_multi_close ( $mh );
  

?>
 



As you can see in the code example we still use the basic Curl functions from the first example to create each curl handle. These handles are put in an array to use later on to retrieve the results. The wait.php script in this example is a simple PHP script which sleeps for the requested amount of seconds to demonstrate how the handles are parallel executed.

In theory the above code will take as long as the slowest request, in this case 5 seconds. However when executing too much parallel requests, using Curl can cause some overhead. Also error handling in the separate requests can be difficult because there's not an easy way to communicate with the 'threads'. Despite these problems Curl is a serious option to consider if you want to use multithreading in PHP.

One final note: this is not 'real' multithreading but a way to offload things into separate PHP requests. This will put some extra strain on your webserver, so please take that into account.

最后附件附上一个多线程的Daemon,来自:http://phpmultithreaddaemon.blogspot.com/
分享到:
评论

相关推荐

    php 多线程

    php 多线程php 多线程php 多线程php 多线程php 多线程

    php多线程获取网页

    php多线程获取网页,利用curl_multi同时请求多个url,并发请求,缩短执行等待时间

    PHP多线程图片处理

    在PHP中实现多线程处理图片是一项挑战,因为PHP本身并不支持原生的多线程。但是,通过一些技巧和扩展,我们可以模拟实现多线程的功能。本篇将深入探讨如何利用CURL扩展来实现这一目标,以及在这个过程中可能遇到的...

    php多线程批量采集下载图片的实现代码函数类.zip

    分享一个使用php多线程批量采集下载图片的实现代码函数类,curl的多线程,另外curl可以设置请求时间,遇到很慢的url资源,可以果断的放弃,这样没有阻塞,另外有多线程请求,效率应该比较高

    php多线程扩展

    首先,"php多线程扩展"指的是PHP的一个特殊模块,它允许PHP代码在运行时创建和管理多个线程,从而实现并发执行任务。这个扩展通常由C语言编写,因为C语言能够提供更底层的访问系统资源的能力,对于实现多线程功能...

    php多线程类库.zip

    在PHP编程中,多线程通常不是其原生支持的功能,因为PHP主要设计为服务器端的脚本语言,主要用于处理单个请求。然而,随着Web应用程序复杂性的增加,开发人员有时候需要并行处理多个任务来提高效率。在这种情况下,...

    php多线程并发实现方法

    在了解PHP多线程并发实现方法之前,首先需要明白PHP语言本身并不是设计为支持传统意义上的多线程并发模型。PHP是一种主要用于Web开发的服务器端脚本语言,它通常以单线程的方式运行。每次有请求进入,PHP都会启动一...

    php多线程类库

    可以参考其中的basic.php实例.php开发者可以通过继承php_fork来封装一个方法,然后通过调用start()方法来产生一个子进程.所产生的进程间的通讯通过共享内存片断来实现,通过使用一个用户自定义的信号量,就能够使使用...

    php_work php实现多线程

    下面是一个简单的使用pthreads的PHP多线程示例: ```php &lt;?php class MyThread extends \Thread { public function __construct($arg) { $this-&gt;arg = $arg; } public function run() { // 在这里执行线程...

    php多线程批量采集下载图片的实现代码函数类

    在PHP中,多线程处理任务通常通过pthreads扩展来实现,这在处理大量I/O密集型任务,如批量采集和下载图片时非常有用。由于PHP本身是单线程的,使用多线程可以显著提高并发性和执行效率。在描述中提到了curl库的多...

    php多线程请求url数据(get)共2页.pdf.zip

    这里,我们讨论的主题是“php多线程请求url数据(get)”,这表明我们将关注如何在PHP中使用多线程技术来并发地获取HTTP GET请求的数据。 PHP本身并不直接支持多线程,因为它是单线程的语言。但是,我们可以借助一些...

    PHP多线程抓取多个网页及获取数据的通用方法.pdf

    PHP多线程抓取多个网页及获取数据的通用方法 本文将详细介绍如何使用PHP多线程抓取多个网页及获取数据的通用方法,并通过实例演示如何使用CURL多线程抓取Adobe公司提供的免費网络相册的图片外链地址。 多线程抓取...

    php多线程,可定制爬虫框架 .zip

    本项目名为“php多线程,可定制爬虫框架”,意味着它是一个基于PHP编程语言的多线程爬虫解决方案,允许用户根据自身需求进行定制。下面将详细探讨PHP爬虫的实现、多线程的优势以及如何进行框架的定制。 首先,让...

    php的curl多线程采集

    ### PHP多线程扩展 PHP默认不支持真正的多线程,但可以通过以下两种方式实现: 1. **pthreads扩展**:这是一个用户空间的线程实现,可以创建线程对象并实现同步机制。每个线程可以拥有自己的`cURL`会话,实现并行...

    php利用curl实现多线程下载图片类

    通过WEB服务器来实现PHP多线程功能,当然,对多线程有深入理解的人都知道通过WEB服务器实现的多线程只能模仿多线程的一些效果,并不是真正意义上的多线程。利用curl实现多线程下载图片类,其实是php利用curl实现的一个...

    PHP多线程编程之管道通信实例分析_.docx

    本文将深入探讨PHP多线程编程中的管道通信,并通过一个实例进行详细分析。 管道通信是一种简单的进程间通信机制,它允许不同进程(或线程)之间共享数据。在PHP中,我们通常使用POSIX标准的`posix_mkfifo()`函数...

    PHP多线程HTTP下载工具

    完全使用PHP编写的多线程下载工具,带有Web控制台。因为时间关系,控制台界面直接使用了Transmission的UI,操作方法也和Transmission类似。 多平台支持: Windows、Unix\Linux,甚至是路由器等设备(我就是为路由器写...

    CurlMulti 一个php多线程类库

    CurlMulti是PHP中用于处理HTTP请求的多线程库,尤其在进行批量数据抓取或需要并发执行多个HTTP操作时非常有用。它基于libcurl库,提供了对curl_multi_init(), curl_multi_add_handle(), curl_multi_exec(), 和curl_...

Global site tag (gtag.js) - Google Analytics