Table of Contents
1. Three methods of php simulation to achieve multi-threading
2. The real way to realize php multi-threading
Home Backend Development PHP Tutorial PHP multi-threading solution sharing

PHP multi-threading solution sharing

Mar 22, 2018 am 10:30 AM
php share solution

We all know that php itself does not support multi-threading, so how should we implement multi-threading in php? In this article, we mainly share with you the PHP multi-threading solution, hoping to help you.

1. Three methods of php simulation to achieve multi-threading

1. PHP multi-threading under Linux

The following things are the source Since PHP's pcntl_fork function. Because this function depends on the implementation of operating system fork, the things discussed in this article only apply to Linux/Unix. So let’s take a look at the usage of this function first. The PHP manual says this:

<?php$pid = pcntl_fork();if ($pid == -1) {        
 die(&#39;could not fork&#39;);
} else if ($pid) {        
// we are the parent
         pcntl_wait($status); 
         //Protect against Zombie children} else {       
           // we are the child}?>
Copy after login

Create a child process through pcntl_fork. If the return value is -1, then the creation of the child process failed. The creation was successful. The process ID will be returned to the parent process, and 0 will be returned to the child process. It is difficult to understand, so it should be written like this:

<?php$pid = pcntl_fork();if($pid == -1){         //创建失败咱就退出呗,没啥好说的
         die(&#39;could not fork&#39;);
}else{        if($pid){                //从这里开始写的代码是父进程的,因为写的是系统程序,记得退出的时候给个返回值
                exit(0);
        }        else{                //从这里开始写的代码都是在新的进程里执行的,同样正常退出的话,最好也给一个返回值
                exit(0);
        }
}?>
Copy after login

This change will make it easier to understand, if your parent process wants to know that the child process exits normally. , you can add the previous pcntl_wait.

2.Through stream_socket_client method

function sendStream() { 
    $english_format_number = number_format($number, 4, &#39;.&#39;, &#39;&#39;); 
  
    echo $english_format_number;  
    exit(); 
    $timeout = 10; 
    $result = array(); 
    $sockets = array(); 
    $convenient_read_block = 8192; 
    $host = "test.local.com"; 
    $sql = "select waybill_id,order_id from xm_waybill where status>40 order by update_time desc limit 1 ";  
    $data = Yii::app()->db->createCommand($sql)->queryAll(); 
    $id = 0; 
  
    foreach ($data as $k => $v) { 
      if ($k % 2 == 0) { 
        $send_data[$k][&#39;body&#39;] = NoticeOrder::getSendData($v[&#39;waybill_id&#39;]); 
  
      } else { 
        $send_data[$k][&#39;body&#39;] = array($v[&#39;order_id&#39;] => array(&#39;extra&#39; => 16));  
      }  
      $data = json_encode($send_data[$k][&#39;body&#39;]); 
      $s = stream_socket_client($host . ":80", $errno, $errstr, $timeout, STREAM_CLIENT_ASYNC_CONNECT | STREAM_CLIENT_CONNECT); 
      if ($s) {  
        $sockets[$id++] = $s; 
        $http_message = "GET /php/test.php?data=" . $data . " HTTP/1.0\r\nHost:" . $host . "\r\n\r\n";  
        fwrite($s, $http_message); 
      } else {  
        echo "Stream " . $id . " failed to open correctly."; 
      }  
    } 
  
    while (count($sockets)) { 
  
      $read = $sockets; 
  
      stream_select($read, $w = null, $e = null, $timeout); 
       if (count($read)) {  
        /* stream_select generally shuffles $read, so we need to 
         compute from which socket(s) we&#39;re reading. */
        foreach ($read as $r) { 
  
          $id = array_search($r, $sockets); 
          $data = fread($r, $convenient_read_block); 
          if (strlen($data) == 0) { 
            echo "Stream " . $id . " closes at " . date(&#39;h:i:s&#39;) . ".<br>  "; 
            fclose($r); 
             unset($sockets[$id]); 
          } else { 
            $result[$id] = $data; 
          } 
        } 
      } else {  
        /* A time-out means that *all* streams have failed 
         to receive a response. */
        echo "Time-out!\n"; 
        break; 
      }  
    }  
    print_r($result); 
  
  }
Copy after login

3. Through multi-process instead of multi-thread

function daemon($func_name,$args,$number){ 
  while(true){ 
    $pid=pcntl_fork(); 
    if($pid==-1){ 
      echo "fork process fail"; 
      exit(); 
    }elseif($pid){//创建的子进程 
  
      static $num=0; 
      $num++; 
      if($num>=$number){ 
        //当进程数量达到一定数量时候,就对子进程进行回收。 
        pcntl_wait($status); 
  
        $num--; 
      }  
    }else{ //为0 则代表是子进程创建的,则直接进入工作状态 
  
      if(function_exists($func_name)){ 
        while (true) { 
          $ppid=posix_getpid(); 
          var_dump($ppid); 
          call_user_func_array($func_name,$args); 
          sleep(2); 
        } 
      }else{ 
        echo "function is not exists"; 
      } 
      exit();   
    } 
  } 
}  
function worker($args){  
  //do something 
  }  
daemon(&#39;worker&#39;,array(1),2);
Copy after login

2. The real way to realize php multi-threading

The real way to realize php multi-threading can be done by installing the php extension pthread.

PHP multi-threading solution sharing

Then refresh the page as follows, drag to the bottom:

PHP multi-threading solution sharing



PHP multi-threading solution sharing

##Find version 2 on the next page

Download, this v2 can only be used with php5

Download Come down and install:

Or, you can download it directly like this:

cd /tools  
   wget https://github.com/krakjoe/pthreads/archive/v2.0.10.zip  
   unzip   v2.0.10.zip  
   cd pthreads-2.0.10  
   /usr/local/php/bin/phpize  
   ./configure --with-php-config=/usr/local/php/bin/php-config    
   make  
   make install
Copy after login

Note: Your php needs to be enabled-enable-maintainer-zts when compiling


./configure --prefix=/usr/local/php --disable-fileinfo   --enable-fpm --with-config-file-path=/etc --with-config-file-scan-dir=/etc/php.d --with-openssl --with-zlib --with-curl --enable-ftp --with-gd --with-xmlrpc  --with-jpeg-dir --with-png-dir --with-freetype-dir --enable-gd-native-ttf --enable-mbstring --with-mcrypt=/usr/local/libmcrypt --enable-zip --with-mysql=/usr/local/mysql --without-pear --enable-maintainer-zts
Copy after login
vim /etc/php.ini 
添加
extension=pthreads.so
Copy after login
重启php  
/etc/init.d/php-fpm restart
Copy after login
Related recommendations:

Detailed explanation of the multi-threading mechanism of the browser

Detailed explanation of php multi-threading examples

##PHP Support for multi-threaded programming and usage

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

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

CakePHP Project Configuration CakePHP Project Configuration Sep 10, 2024 pm 05:25 PM

In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP.

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

CakePHP Routing CakePHP Routing Sep 10, 2024 pm 05:25 PM

In this chapter, we are going to learn the following topics related to routing ?

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

See all articles