>  기사  >  백엔드 개발  >  PHP에서 진정한 멀티스레딩 사용

PHP에서 진정한 멀티스레딩 사용

WBOY
WBOY원래의
2016-08-08 09:20:221010검색
pthreads PHP 확장을 사용하는 PHP 5.3 이상에서는 PHP가 진정한 멀티스레딩을 지원하도록 할 수 있습니다. 멀티스레딩은 반복적인 순환 작업을 처리할 때 프로그램 실행 시간을 크게 단축할 수 있습니다.
이전 기사에서 대부분의 웹사이트의 성능 병목 현상은 PHP 서버에서 발생하지 않는다고 말씀드렸는데, 이는 서버나 CPU 코어 수를 수평적으로 늘리는 것만으로 쉽게 처리할 수 있기 때문입니다(다양한 경우). 클라우드 호스트의 경우 VPS 또는 CPU 코어 수를 늘리는 것이 더 편리합니다. 운영 체제 및 환경을 설치하고 구성할 필요도 없지만 MySQL 데이터베이스를 사용하여 VPS를 직접 추가할 수 있습니다. MySQL 데이터베이스와 공동 쿼리 SQL을 사용하면 비즈니스 로직을 처리할 수 있지만 동시에 많은 요청이 발생하면 작업이 중단됩니다. NoSQL을 사용하는 경우 데이터베이스는 동일한 비즈니스 로직을 처리하기 위해 10개의 쿼리가 필요할 수 있지만 각 쿼리는 MySQL보다 빠릅니다. 10개의 루프 NoSQL 쿼리는 MySQL 공동 쿼리보다 빠를 수 있으며 초당 수만 개의 쿼리를 처리하는 것은 전혀 쓸모가 없습니다. . PHP 멀티스레딩을 추가하고 동시에 10개의 스레드를 통해 NoSQL을 쿼리하고 결과 요약 출력을 반환하면 속도가 더 빨라집니다. 실제 APP 제품에서는 사용자 선호도에 따라 실시간으로 제품을 추천하는 PHP 인터페이스를 호출합니다. PHP는 사용자의 개인화된 선호도 제품 데이터를 실시간으로 계산하기 위해 BigSea NoSQL 데이터베이스에 500~1,000개의 쿼리를 시작해야 합니다. PHP 멀티스레딩은 매우 분명합니다.
PHP 확장 다운로드: https://github.com/krakjoe/pthreads
PHP 매뉴얼 문서: http:// php.net/manual/zh/book.pthreads.php
1. 확장 컴파일 및 설치(Linux), --enable-maintainer-zts 매개변수 편집은 필수 옵션입니다.

cd /Data/tgz/php-5.5.1
./configure --prefix=/Data/apps/php --with-config-file-path=/Data/apps/ php /etc --with-mysql=/Data/apps/mysql --with-mysqli=/Data/apps/mysql/bin/mysql_config --with-iconv-dir --with-freetype-dir=/Data/apps / libs --with-jpeg-dir=/Data/apps/libs --with-png-dir=/Data/apps/libs --with-zlib --with-libxml-dir=/usr --enable-xml --disable-rpath --enable-bcmath --enable-shmop --enable-sysvsem --enable-inline-optimization --with -curl --enable-mbregex --enable-fpm --enable-mbstring --with-mcrypt=/Data/apps/libs --with-gd --enable-gd-native-ttf --with-openssl --with-mhash --enable-pcntl --enable-sockets --with-xmlrpc --enable-zip --enable-soap --enable-opcache --with-pdo-mysql --enable -maintainer-zts
make clean
make
make install
unzip pthreads-master.zip
cd pthreads-master
/Data/apps/php/bin/phpize
./configure --with-php-c/apps/php/bin/php-config
make
make install


vi /Data/apps/php/etc /php.ini


추가:

extension = "pthreads.so"


2. PHP 섹션 스레드 제공 및 For 루프, Baidu 검색 페이지를 가져오기 위한 PHP 코드 예제:

<?php
&#160;&#160;class test_thread_run extends Thread 
&#160;&#160;{
&#160;&#160;&#160;&#160;&#160;&#160;public $url;
&#160;&#160;&#160;&#160;&#160;&#160;public $data;

&#160;&#160;&#160;&#160;&#160;&#160;public function __construct($url)
&#160;&#160;&#160;&#160;&#160;&#160;{
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;$this->url = $url;
      }

      public function run()
      {
          if(($url = $this->url))
          {
              $this->data = model_http_curl_get($url);
          }
      }
  }

  function model_thread_result_get($urls_array) 
  {
      foreach ($urls_array as $key => $value) 
      {
          $thread_array[$key] = new test_thread_run($value["url"]);
          $thread_array[$key]->start();
      }

      foreach ($thread_array as $thread_array_key => $thread_array_value) 
      {
          while($thread_array[$thread_array_key]->isRunning())
          {
              usleep(10);
          }
          if($thread_array[$thread_array_key]->join())
          {
              $variable_data[$thread_array_key] = $thread_array[$thread_array_key]->data;
          }
      }
      return $variable_data;
  }

  function model_http_curl_get($url,$userAgent="") 
  {
      $userAgent = $userAgent ? $userAgent : 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2)'; 
      $curl = curl_init();
      curl_setopt($curl, CURLOPT_URL, $url);
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($curl, CURLOPT_TIMEOUT, 5);
      curl_setopt($curl, CURLOPT_USERAGENT, $userAgent);
      $result = curl_exec($curl);
      curl_close($curl);
      return $result;
  }

  for ($i=0; $i < 100; $i++) 
&#160;&#160;{ 
&#160;&#160;&#160;&#160;&#160;&#160;$urls_array[] = array("name" => "baidu", "url" => "http://www.baidu.com/s?wd=".mt_rand(10000,20000));
  }

  $t = microtime(true);
  $result = model_thread_result_get($urls_array);
  $e = microtime(true);
  echo "多线程:".($e-$t)."\n";

  $t = microtime(true);
  foreach ($urls_array as $key => $value) 
  {
      $result_new[$key] = model_http_curl_get($value["url"]);
  }
  $e = microtime(true);
  echo "For循环:".($e-$t)."\n";
?>

위에서는 PHP의 진정한 멀티스레딩 사용 방법을 소개했으며, PHP 튜토리얼에 관심이 있는 친구들에게 도움이 되기를 바랍니다.

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.