首頁  >  文章  >  後端開發  >  簡單的php多執行緒解決方法

簡單的php多執行緒解決方法

烟雨青岚
烟雨青岚轉載
2020-06-16 13:15:404755瀏覽

簡單的php多執行緒解決方法

簡單的php多執行緒解決方法

#我們在做專案的時候,有些需求,特別是數據的回應處理需要花費大量的時間,由於php是一個短生命週期的腳本語言,到了預設的30秒,php的資料處理還沒完成,php的生命週期就結束了。

這時需要使用非同步並發處理策略,也就是說,一次php呼叫可以發出的多個請求,這些請求不是按照順序執行,而是可以非同步並發執行的,一些請求用於在後台處理數據,一些請求用於接受後台回應狀態,根據狀態,與用戶做一些簡單的互動。

但是問題來了,我們都知道php本身是不支援多執行緒的,那麼我們該怎麼實作php的多執行緒呢?

一、php模擬實作多執行緒的三種方法

1、linux下的php多執行緒

下面所講的東西是來源自php的pcntl_fork函數.因為這個函數依賴作業系統fork的實作,所以本文所講的東西只適用於linux/unix。那麼先看看這個函數的用法吧.php手冊上是這麼說的:

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

透過pcntl_fork創建一個子進程,如果返回值是-1的話,那麼說明子進程創建失敗.創建成功的進程id會回傳給父進程,0回傳給子進程.不好理解吧,所以應該這樣寫:

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

這樣一改好理解多了,如果你父進程希望知道子進程正常退出的話,可以加上前面的pcntl_wait。

2.透過stream_socket_client 方式

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
Host:" . $host . "
";  
        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!
"; 
        break; 
      }  
    }  
    print_r($result); 
  
  }

3、透過多進程取代多執行緒

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

#二、真正實作php多執行緒的方法

php真正的多執行緒實作方式,透過安裝php的擴充pthread 可以做到。

點此下載https://github.com/krakjoe/pthreads   但是這個下載的是版本3 也就是php 7 才能用的,我們需要讓的是版本2  

簡單的php多執行緒解決方法

#然後重新整理的頁面如下,拖曳到最底部:  

簡單的php多執行緒解決方法

簡單的php多執行緒解決方法

#下一頁找到版本2的

下載下來,這個v2 才是php5才可以使用的

下載下來,安裝:

或者,您直接這樣下載:

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

注意:您的php 在編譯的時候需要開啟–enable-maintainer-zts

./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

vim /etc/php.ini 
添加
extension=pthreads.so

重啟php /etc/init.d/php-fpm restart

感謝大家的閱讀,希望大家收益多多。

推薦教學:《php教學

以上是簡單的php多執行緒解決方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:51dev.com。如有侵權,請聯絡admin@php.cn刪除