PHP implements multi-threaded code

不言
Release: 2023-03-23 21:14:01
Original
1561 people have browsed it

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);
        }
      }
    }
  }
}
Copy after login


## 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);
}
?>
Copy after login

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;  
  }
Copy after login
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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!