search
HomeBackend DevelopmentPHP TutorialThree similar methods to achieve multi-threading in PHP

1. curl_multi method

When multi-threading is required, curl_multi can be used to request multiple operations at one time, but curl uses network communication, so the efficiency and reliability are relatively poor.

function main(){
  
   $sql = "select waybill_id,order_id from waybill where status>40 order by update_time desc limit 10 ";
  
    $data = Yii::app()->db->createCommand($sql)->queryAll(); //yii 框架格式
  
    foreach ($data as $k => $v) { 
  
      if ($k % 2 == 0) { //偶数发一个网址
  
        $send_data[$k]['url'] = '';
  
        $send_data[$k]['body'] = $v['waybill_id'];
  
      } else { //奇数发送另外一个网址
        $send_data[$k]['url'] = 'http://www.abc.com';
  
        $send_data[$k]['body']=array($v['order_id'] => array('extra' => 16));
  
      }
  
    }
 
    $back_data =sendMulitRequest($send_data);
  
    var_dump($back_data);
  
  }
  function sendMulitRequest($send_data){
    $params = array();
    $curl = $text = array();
    $handle = curl_multi_init();
  
    foreach ($data as $k => $v) {
  
      if (empty($v['url'])) {
  
        $v['url'] = "http://www.xxx.com"; //if url is empty,set defalut url
  
      }
  
      $reqBody = json_encode($v['body']);
  
      $reqStream = array(
  
        'body' => $reqBody,
      ); 
      $encRequest = base64_encode(json_encode($reqStream)); 
      $params['data'] = $encRequest;
      $curl[$k] = curl_init();
      curl_setopt($curl[$k], CURLOPT_URL, $v['url']);
      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; 
  }

2. Through stream_socket_client method

function sendStream() {
    $english_format_number = number_format($number, 4, '.', '');
  
    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]['body'] = NoticeOrder::getSendData($v['waybill_id']);
  
      } else {
        $send_data[$k]['body'] = array($v['order_id'] => array('extra' => 16)); 
      } 
      $data = json_encode($send_data[$k]['body']);
      $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'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);
  
  }

3. Replace multi-threading through multi-process

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

The above are the three ways to implement multi-threading in PHP Similar method, I hope it will be helpful to everyone's study.

For more related articles on three similar methods of implementing multi-threading in PHP, please pay attention to the PHP Chinese website!


Statement
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
What data can be stored in a PHP session?What data can be stored in a PHP session?May 02, 2025 am 12:17 AM

PHPsessionscanstorestrings,numbers,arrays,andobjects.1.Strings:textdatalikeusernames.2.Numbers:integersorfloatsforcounters.3.Arrays:listslikeshoppingcarts.4.Objects:complexstructuresthatareserialized.

How do you start a PHP session?How do you start a PHP session?May 02, 2025 am 12:16 AM

TostartaPHPsession,usesession_start()atthescript'sbeginning.1)Placeitbeforeanyoutputtosetthesessioncookie.2)Usesessionsforuserdatalikeloginstatusorshoppingcarts.3)RegeneratesessionIDstopreventfixationattacks.4)Considerusingadatabaseforsessionstoragei

What is session regeneration, and how does it improve security?What is session regeneration, and how does it improve security?May 02, 2025 am 12:15 AM

Session regeneration refers to generating a new session ID and invalidating the old ID when the user performs sensitive operations in case of session fixed attacks. The implementation steps include: 1. Detect sensitive operations, 2. Generate new session ID, 3. Destroy old session ID, 4. Update user-side session information.

What are some performance considerations when using PHP sessions?What are some performance considerations when using PHP sessions?May 02, 2025 am 12:11 AM

PHP sessions have a significant impact on application performance. Optimization methods include: 1. Use a database to store session data to improve response speed; 2. Reduce the use of session data and only store necessary information; 3. Use a non-blocking session processor to improve concurrency capabilities; 4. Adjust the session expiration time to balance user experience and server burden; 5. Use persistent sessions to reduce the number of data read and write times.

How do PHP sessions differ from cookies?How do PHP sessions differ from cookies?May 02, 2025 am 12:03 AM

PHPsessionsareserver-side,whilecookiesareclient-side.1)Sessionsstoredataontheserver,aremoresecure,andhandlelargerdata.2)Cookiesstoredataontheclient,arelesssecure,andlimitedinsize.Usesessionsforsensitivedataandcookiesfornon-sensitive,client-sidedata.

How does PHP identify a user's session?How does PHP identify a user's session?May 01, 2025 am 12:23 AM

PHPidentifiesauser'ssessionusingsessioncookiesandsessionIDs.1)Whensession_start()iscalled,PHPgeneratesauniquesessionIDstoredinacookienamedPHPSESSIDontheuser'sbrowser.2)ThisIDallowsPHPtoretrievesessiondatafromtheserver.

What are some best practices for securing PHP sessions?What are some best practices for securing PHP sessions?May 01, 2025 am 12:22 AM

The security of PHP sessions can be achieved through the following measures: 1. Use session_regenerate_id() to regenerate the session ID when the user logs in or is an important operation. 2. Encrypt the transmission session ID through the HTTPS protocol. 3. Use session_save_path() to specify the secure directory to store session data and set permissions correctly.

Where are PHP session files stored by default?Where are PHP session files stored by default?May 01, 2025 am 12:15 AM

PHPsessionfilesarestoredinthedirectoryspecifiedbysession.save_path,typically/tmponUnix-likesystemsorC:\Windows\TemponWindows.Tocustomizethis:1)Usesession_save_path()tosetacustomdirectory,ensuringit'swritable;2)Verifythecustomdirectoryexistsandiswrita

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools