Summary of php implementation multi-threaded methods

Source: Internet
Author: User
It is clear that php does not support multithreading. However, it is a headache for people who need a multi-threaded feature. Fortunately, there are several solutions that can be solved, similar to multithreading. The following are my summary of the three methods to achieve multithreading similar solutions, the following are three solutions and code... "/> <scripttype =" text/javascript "src =" http: // www.2cto

It is clear that php does not support multithreading. However, it is a headache for people who need a multi-threaded feature. Fortunately, there are several solutions that can be solved, similar to multithreading. The following are my summary of the three methods for implementing multithreading similar methods. The following are three solutions and code examples.

1. curl_multi method

When multithreading is required, you can use curl_multi to request multiple operations at a time. However, curl uses network communication, and 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 Framework format foreach ($ data as $ k => $ v) {if ($ k % 2 = 0) {// send an even url $ send_data [$ k] ['URL'] = ''; $ send_data [$ k] ['body'] = $ v ['waybill _ id'];} else {// send another url with an odd number $ 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_POSTFIE LDS, 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;} 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 Framework format foreach ($ data as $ k => $ v) {if ($ k % 2 = 0) {// send an even url $ send_data [$ k] ['URL'] = ''; $ send_data [$ k] ['body'] = $ v ['waybill _ id'];} else {// send another url with an odd number $ 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_POSTFIE LDS, 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. stream_socket_client

 

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('h:i:s') . ".
"; 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); } 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('h:i:s') . ".
"; 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 multithreading with multiple processes

Function daemon ($ func_name, $ args, $ number) {while (true) {$ pid = pcntl_fork (); if ($ pid =-1) {echo "fork process fail"; exit () ;}elseif ($ pid) {// The created sub-process static $ num = 0; $ num ++; if ($ num >=$ number) {// when the number of processes reaches a certain number, the child processes are recycled. Pcntl_wait ($ status); $ num -- ;}} else {// if it is 0, it indicates that it was created by a sub-process and directly enters the working state 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 ('worker ', array (1), 2); function daemon ($ func_name, $ args, $ number) {while (true) {$ pid = pcntl_fork (); If ($ pid =-1) {echo "fork process fail"; exit ();} elseif ($ pid) {// created sub-process static $ num = 0; $ num ++; if ($ num >=$ number) {// when the number of processes reaches a certain number, the sub-process is recycled. Pcntl_wait ($ status); $ num -- ;}} else {// if it is 0, it indicates that it was created by a sub-process and directly enters the working state 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 ('worker ', array (1), 2 );

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.