您好,登錄后才能下訂單哦!
小編給大家分享一下php多線程有哪些實(shí)現(xiàn)方法,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
1、curl_multi方法
當(dāng)需要多線程的時(shí)候,可以用curl_multi一次性請(qǐng)求多個(gè)操作來完成,但curl走的是網(wǎng)絡(luò)通信,效率與可靠性就比較差了的。
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) { //偶數(shù)發(fā)一個(gè)網(wǎng)址 $send_data[$k]['url'] = ''; $send_data[$k]['body'] = $v['waybill_id']; } else { //奇數(shù)發(fā)送另外一個(gè)網(wǎng)址 $send_data[$k]['url'] = 'http://www.abc.com'; $send_data[$k]['body']=array($v['order_id'] => array('extra' => 16)); } } }
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."; } } }
3、通過多進(jìn)程代替多線程
function daemon($func_name,$args,$number){ while(true){ $pid=pcntl_fork(); if($pid==-1){ echo "fork process fail"; exit(); }elseif($pid){//創(chuàng)建的子進(jìn)程 static $num=0; $num++; if($num>=$number){ //當(dāng)進(jìn)程數(shù)量達(dá)到一定數(shù)量時(shí)候,就對(duì)子進(jìn)程進(jìn)行回收。 pcntl_wait($status); $num--; } }else{ //為0 則代表是子進(jìn)程創(chuàng)建的,則直接進(jìn)入工作狀態(tài) 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);
以上是php多線程有哪些實(shí)現(xiàn)方法的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。