>  기사  >  백엔드 개발  >  pthread를 사용하여 진정한 PHP 멀티스레딩을 구현하는 방법

pthread를 사용하여 진정한 PHP 멀티스레딩을 구현하는 방법

不言
不言원래의
2018-07-03 16:18:104021검색

이 글은 실제 PHP 멀티스레딩을 구현하기 위해 pthread를 사용하는 방법을 주로 소개합니다. 이제 필요한 친구들이 참고할 수 있도록 공유하겠습니다.

PSP 5.3 이상에서는 pthreads PHP를 사용하세요. 확장 기능을 사용하여 PHP가 진정한 멀티스레딩을 지원하도록 만드세요. 멀티스레딩은 반복적인 순환 작업을 처리할 때 프로그램 실행 시간을 크게 단축할 수 있습니다

이전 기사에서 대부분의 웹사이트의 성능 병목 현상은 단순히 서버나 CPU 코어 수를 수평적으로 늘릴 수 있기 때문에 PHP 서버에서 발생하지 않는다고 말씀드렸습니다. (다양한 클라우드 호스트의 경우 VPS 또는 CPU 코어를 추가하는 것이 더 편리합니다. 운영 체제 및 환경을 설치 및 구성할 필요 없이 백업 이미지로 직접 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는 필수 옵션입니다. php.ini에 추가된

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-config=/Data/apps/php/bin/php-config
make
make install

:

vi /Data/apps/php/etc/php.ini
extension = "pthreads.so"

는 PHP 멀티스레딩을 제공하고 For 루프에서는 Baidu 검색을 위한 PHP 코드 예제를 제공합니다. page :

<?php
  class test_thread_run extends Thread 
  {
      public $url;
      public $data;
      public function __construct($url)
      {
          $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 : &#39;Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2)&#39;; 
      $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++) 
  { 
      $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)."
";
  $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)."
";
?>

위 내용은 모두의 학습에 도움이 되기를 바랍니다. 더 많은 관련 내용은 PHP 중국어 홈페이지를 주목해주세요! Related Related Residentations : phpp

introduction에서 CSV 파일을 가져올 때 ThinkPhp의 이메일을 전자 메일 전송을위한 암호 검색 기능으로 가져올 때 garbled 문자 문제를 해결하는 방법


위 내용은 pthread를 사용하여 진정한 PHP 멀티스레딩을 구현하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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