Home >Backend Development >PHP Tutorial >PHP implements multi-threaded code

PHP implements multi-threaded code

不言
不言Original
2018-04-14 16:52:261617browse

The content shared with you in this article is about the implementation of multi-threaded code in PHP. It has certain reference value. Friends in need can refer to it

PHP itself does not support multi-threading For threads, we can handle multi-threading virtually through PHP's own functions. Three functions are introduced below to implement multi-processing.


1. fsockopen, open a network connection or a Unix socket connection. Among them, stream_set_blocking() - sets blocking or blocking mode for resource flow


* @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);
        }
      }
    }
  }
}


## 2. stream_socket_client, the new stream_socket_client can be used in PHP5 () function directly replaces fsocketopen(). Among them, stream_set_blocking() - sets blocking or blocking mode for resource flow



<?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);
}
?>

3. curl_multi, when multiple threads are needed, curl_multi can be used once It requires multiple operations to complete, but curl uses network communication, so the efficiency and reliability are relatively poor.


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;  
  }

Related recommendations:

php multi-threaded php fsockopen solution

The above is the detailed content of PHP implements multi-threaded code. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn