首页  >  文章  >  后端开发  >  php实现多线程代码

php实现多线程代码

不言
不言原创
2018-04-14 16:52:261589浏览

本篇文章给大家分享的内容是关于php实现多线程代码,有着一定的参考价值,有需要的朋友可以参考一下

PHP本身是不支持多线程的,我们可以通过php自身函数虚拟处理啊多线程。下面介绍三个函数来实现多进程。


一、fsockopen,打开一个网络连接或者一个Unix套接字连接。其中stream_set_blocking() - 为资源流设置阻塞或者阻塞模式


* @title:   PHP多线程类(Thread)
 * @version:  1.0
 * 
 * PHP多线程应用示例:
 * require_once 'thread.class.php';
 * $thread = new thread();
 * $thread->addthread('action_log','a');
 * $thread->addthread('action_log','b');
 * $thread->addthread('action_log','c');
 * $thread->runthread();
 * 
 * function action_log($info) {
 *   $log = 'log/' . microtime() . '.log';
 *   $txt = $info . "rnrn" . 'Set in ' . Date('h:i:s', time()) . (double)microtime() . "rn";
 *   $fp = fopen($log, 'w');
 *   fwrite($fp, $txt);
 *   fclose($fp);
 * }
 */
class thread {
  
  var $hooks = array();
  var $args = array();
  
  function thread() {
  }
  
  function addthread($func)
  {
    $args = array_slice(func_get_args(), 1);
    $this->hooks[] = $func;
    $this->args[] = $args;
    return true;
  }
  
  function runthread()
  {
    if(isset($_GET['flag']))
    {
      $flag = intval($_GET['flag']);
    }
    if($flag || $flag === 0)
    {
      call_user_func_array($this->hooks[$flag], $this->args[$flag]);
    }
    else
    {
      for($i = 0, $size = count($this->hooks); $i < $size; $i++)
      {
        $fp=fsockopen($_SERVER[&#39;HTTP_HOST&#39;],$_SERVER[&#39;SERVER_PORT&#39;]);
        stream_set_blocking($fp,0);
        if($fp)
        {
          $out = "GET {$_SERVER[&#39;PHP_SELF&#39;]}?flag=$i HTTP/1.1rn";
          $out .= "Host: {$_SERVER[&#39;HTTP_HOST&#39;]}rn";
          $out .= "Connection: Closernrn";
          fputs($fp,$out);
          fclose($fp);
        }
      }
    }
  }
}


二、stream_socket_client,PHP5中可以使用新增的stream_socket_client()函数直接替换掉fsocketopen()。其中stream_set_blocking() - 为资源流设置阻塞或者阻塞模式


<?php
$fp = stream_socket_client("tcp://www.example.com:80", $errno, $errstr, 30);
stream_set_blocking($fp,0);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    fwrite($fp, "GET / HTTP/1.0\r\nHost: www.example.com\r\nAccept: */*\r\n\r\n");
    while (!feof($fp)) {
        echo fgets($fp, 1024);
    }
    fclose($fp);
}
?>


三、curl_multi,当需要多线程的时候,可以用curl_multi一次性请求多个操作来完成,但curl走的是网络通信,效率与可靠性就比较差了的。


function sendMulitRequest($send_data){ 
    $params = array(); 
    $curl = $text = array(); 
    $handle = curl_multi_init(); 
  
    foreach ($data as $k => $v) { 
  
      if (empty($v[&#39;url&#39;])) { 
  
        $v[&#39;url&#39;] = "http://www.xxx.com"; //if url is empty,set defalut url 
  
      } 
  
      $reqBody = json_encode($v[&#39;body&#39;]); 
  
      $reqStream = array( 
  
        &#39;body&#39; => $reqBody, 
      );  
      $encRequest = base64_encode(json_encode($reqStream));  
      $params[&#39;data&#39;] = $encRequest; 
      $curl[$k] = curl_init(); 
      curl_setopt($curl[$k], CURLOPT_URL, $v[&#39;url&#39;]); 
      curl_setopt($curl[$k], CURLOPT_POST, TRUE); 
      curl_setopt($curl[$k], CURLOPT_HEADER, 0); 
      curl_setopt($curl[$k], CURLOPT_POSTFIELDS, http_build_query($params)); 
      curl_setopt($curl[$k], CURLOPT_RETURNTRANSFER, 1); 
      curl_multi_add_handle($handle, $curl[$k]); 
    } 
    $active = null; 
  
    do { 
  
      $mrc = curl_multi_exec($handle, $active); 
  
    } while ($mrc == CURLM_CALL_MULTI_PERFORM); 
    while ($active && $mrc == CURLM_OK) { 
  
      if (curl_multi_select($handle) != -1) { 
  
        do { 
  
          $mrc = curl_multi_exec($handle, $active); 
  
        } while ($mrc == CURLM_CALL_MULTI_PERFORM); 
  
      } 
  
    } 
    foreach ($curl as $k => $v) {  
      if (curl_error($curl[$k]) == "") { 
        $text[$k] = (string) curl_multi_getcontent($curl[$k]); 
       }  
      curl_multi_remove_handle($handle, $curl[$k]);  
      curl_close($curl[$k]); 
    } 
    curl_multi_close($handle);  
    return $text;  
  }

相关推荐:

php多线程php fsockopen解决办法

以上是php实现多线程代码的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn