PHP編程中嘗試程序并發(fā)的幾種方式總結(jié),php編程_PHP教程
Jul 12, 2016 am 08:56 AMPHP編程中嘗試程序并發(fā)的幾種方式總結(jié),php編程
本文大約總結(jié)了PHP編程中的五種并發(fā)方式:
1.curl_multi_init
文檔中說(shuō)的是 Allows the processing of multiple cURL handles asynchronously. 確實(shí)是異步。這里需要理解的是select這個(gè)方法,文檔中是這么解釋的Blocks until there is activity on any of the curl_multi connections.。了解一下常見(jiàn)的異步模型就應(yīng)該能理解,select, epoll,都很有名
<?php // build the individual requests as above, but do not execute them $ch_1 = curl_init('http://www.bkjia.com/'); $ch_2 = curl_init('http://www.bkjia.com/'); curl_setopt($ch_1, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch_2, CURLOPT_RETURNTRANSFER, true); // build the multi-curl handle, adding both $ch $mh = curl_multi_init(); curl_multi_add_handle($mh, $ch_1); curl_multi_add_handle($mh, $ch_2); // execute all queries simultaneously, and continue when all are complete $running = null; do { curl_multi_exec($mh, $running); $ch = curl_multi_select($mh); if($ch !== 0){ $info = curl_multi_info_read($mh); if($info){ var_dump($info); $response_1 = curl_multi_getcontent($info['handle']); echo "$response_1 \n"; break; } } } while ($running > 0); //close the handles curl_multi_remove_handle($mh, $ch_1); curl_multi_remove_handle($mh, $ch_2); curl_multi_close($mh);
這里我設(shè)置的是,select得到結(jié)果,就退出循環(huán),并且刪除 curl resource, 從而達(dá)到取消http請(qǐng)求的目的。
2.swoole_client
swoole_client提供了異步模式,我竟然把這個(gè)忘了。這里的sleep方法需要swoole版本大于等于1.7.21, 我還沒(méi)升到這個(gè)版本,所以直接exit也可以。
<?php $client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC); //設(shè)置事件回調(diào)函數(shù) $client->on("connect", function($cli) { $req = "GET / HTTP/1.1\r\n Host: www.jb51.net\r\n Connection: keep-alive\r\n Cache-Control: no-cache\r\n Pragma: no-cache\r\n\r\n"; for ($i=0; $i < 3; $i++) { $cli->send($req); } }); $client->on("receive", function($cli, $data){ echo "Received: ".$data."\n"; exit(0); $cli->sleep(); // swoole >= 1.7.21 }); $client->on("error", function($cli){ echo "Connect failed\n"; }); $client->on("close", function($cli){ echo "Connection close\n"; }); //發(fā)起網(wǎng)絡(luò)連接 $client->connect('183.207.95.145', 80, 1);
3.process
哎,竟然差點(diǎn)忘了 swoole_process, 這里就不用 pcntl 模塊了。但是寫(xiě)完發(fā)現(xiàn),這其實(shí)也不算是中斷請(qǐng)求,而是哪個(gè)先到讀哪個(gè),忽視后面的返回值。
<?php $workers = []; $worker_num = 3;//創(chuàng)建的進(jìn)程數(shù) $finished = false; $lock = new swoole_lock(SWOOLE_MUTEX); for($i=0;$i<$worker_num ; $i++){ $process = new swoole_process('process'); //$process->useQueue(); $pid = $process->start(); $workers[$pid] = $process; } foreach($workers as $pid => $process){ //子進(jìn)程也會(huì)包含此事件 swoole_event_add($process->pipe, function ($pipe) use($process, $lock, &$finished) { $lock->lock(); if(!$finished){ $finished = true; $data = $process->read(); echo "RECV: " . $data.PHP_EOL; } $lock->unlock(); }); } function process(swoole_process $process){ $response = 'http response'; $process->write($response); echo $process->pid,"\t",$process->callback .PHP_EOL; } for($i = 0; $i < $worker_num; $i++) { $ret = swoole_process::wait(); $pid = $ret['pid']; echo "Worker Exit, PID=".$pid.PHP_EOL; }
4.pthreads
編譯pthreads模塊時(shí),提示php編譯時(shí)必須打開(kāi)ZTS, 所以貌似必須 thread safe 版本才能使用. wamp中多php正好是TS的,直接下了個(gè)dll, 文檔中的說(shuō)明復(fù)制到對(duì)應(yīng)目錄,就在win下測(cè)試了。 還沒(méi)完全理解,查到文章說(shuō) php 的 pthreads 和 POSIX pthreads是完全不一樣的。代碼有些爛,還需要多看看文檔,體會(huì)一下。
<?php class Foo extends Stackable { public $url; public $response = null; public function __construct(){ $this->url = 'http://www.bkjia.com'; } public function run(){} } class Process extends Worker { private $text = ""; public function __construct($text,$object){ $this->text = $text; $this->object = $object; } public function run(){ while (is_null($this->object->response)){ print " Thread {$this->text} is running\n"; $this->object->response = 'http response'; sleep(1); } } } $foo = new Foo(); $a = new Process("A",$foo); $a->start(); $b = new Process("B",$foo); $b->start(); echo $foo->response;
5.yield
以同步方式書(shū)寫(xiě)異步代碼:
<?php class AsyncServer { protected $handler; protected $socket; protected $tasks = []; protected $timers = []; public function __construct(callable $handler) { $this->handler = $handler; $this->socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); if(!$this->socket) { die(socket_strerror(socket_last_error())."\n"); } if (!socket_set_nonblock($this->socket)) { die(socket_strerror(socket_last_error())."\n"); } if(!socket_bind($this->socket, "0.0.0.0", 1234)) { die(socket_strerror(socket_last_error())."\n"); } } public function Run() { while (true) { $now = microtime(true) * 1000; foreach ($this->timers as $time => $sockets) { if ($time > $now) break; foreach ($sockets as $one) { list($socket, $coroutine) = $this->tasks[$one]; unset($this->tasks[$one]); socket_close($socket); $coroutine->throw(new Exception("Timeout")); } unset($this->timers[$time]); } $reads = array($this->socket); foreach ($this->tasks as list($socket)) { $reads[] = $socket; } $writes = NULL; $excepts= NULL; if (!socket_select($reads, $writes, $excepts, 0, 1000)) { continue; } foreach ($reads as $one) { $len = socket_recvfrom($one, $data, 65535, 0, $ip, $port); if (!$len) { //echo "socket_recvfrom fail.\n"; continue; } if ($one == $this->socket) { //echo "[Run]request recvfrom succ. data=$data ip=$ip port=$port\n"; $handler = $this->handler; $coroutine = $handler($one, $data, $len, $ip, $port); if (!$coroutine) { //echo "[Run]everything is done.\n"; continue; } $task = $coroutine->current(); //echo "[Run]AsyncTask recv. data=$task->data ip=$task->ip port=$task->port timeout=$task->timeout\n"; $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); if(!$socket) { //echo socket_strerror(socket_last_error())."\n"; $coroutine->throw(new Exception(socket_strerror(socket_last_error()), socket_last_error())); continue; } if (!socket_set_nonblock($socket)) { //echo socket_strerror(socket_last_error())."\n"; $coroutine->throw(new Exception(socket_strerror(socket_last_error()), socket_last_error())); continue; } socket_sendto($socket, $task->data, $task->len, 0, $task->ip, $task->port); $deadline = $now + $task->timeout; $this->tasks[$socket] = [$socket, $coroutine, $deadline]; $this->timers[$deadline][$socket] = $socket; } else { //echo "[Run]response recvfrom succ. data=$data ip=$ip port=$port\n"; list($socket, $coroutine, $deadline) = $this->tasks[$one]; unset($this->tasks[$one]); unset($this->timers[$deadline][$one]); socket_close($socket); $coroutine->send(array($data, $len)); } } } } } class AsyncTask { public $data; public $len; public $ip; public $port; public $timeout; public function __construct($data, $len, $ip, $port, $timeout) { $this->data = $data; $this->len = $len; $this->ip = $ip; $this->port = $port; $this->timeout = $timeout; } } function AsyncSendRecv($req_buf, $req_len, $ip, $port, $timeout) { return new AsyncTask($req_buf, $req_len, $ip, $port, $timeout); } function RequestHandler($socket, $req_buf, $req_len, $ip, $port) { //echo "[RequestHandler] before yield AsyncTask. REQ=$req_buf\n"; try { list($rsp_buf, $rsp_len) = (yield AsyncSendRecv($req_buf, $req_len, "127.0.0.1", 2345, 3000)); } catch (Exception $ex) { $rsp_buf = $ex->getMessage(); $rsp_len = strlen($rsp_buf); //echo "[Exception]$rsp_buf\n"; } //echo "[RequestHandler] after yield AsyncTask. RSP=$rsp_buf\n"; socket_sendto($socket, $rsp_buf, $rsp_len, 0, $ip, $port); } $server = new AsyncServer(RequestHandler); $server->Run(); ?>
代碼解讀:
借助PHP內(nèi)置array能力,實(shí)現(xiàn)簡(jiǎn)單的“超時(shí)管理”,以毫秒為精度作為時(shí)間分片;
封裝AsyncSendRecv接口,調(diào)用形如yield AsyncSendRecv(),更加自然;
添加Exception作為錯(cuò)誤處理機(jī)制,添加ret_code亦可,僅為展示之用。
您可能感興趣的文章:
- php session的鎖和并發(fā)
- php解決搶購(gòu)秒殺抽獎(jiǎng)等大流量并發(fā)入庫(kù)導(dǎo)致的庫(kù)存負(fù)數(shù)的問(wèn)題
- php 根據(jù)url自動(dòng)生成縮略圖并處理高并發(fā)問(wèn)題
- php中并發(fā)讀寫(xiě)文件沖突的解決方案
- php并發(fā)對(duì)MYSQL造成壓力的解決方法
- 一個(gè)PHP并發(fā)訪問(wèn)實(shí)例代碼
- PHP curl 并發(fā)最佳實(shí)踐代碼分享
- PHP如何解決網(wǎng)站大流量與高并發(fā)的問(wèn)題
- Nginx+PHP(FastCGI)搭建高并發(fā)WEB服務(wù)器(自動(dòng)安裝腳本)第二版
- 并發(fā)下常見(jiàn)的加鎖及鎖的PHP具體實(shí)現(xiàn)代碼

熱AI工具

Undress AI Tool
免費(fèi)脫衣圖片

Undresser.AI Undress
人工智慧驅(qū)動(dòng)的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費(fèi)的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門(mén)文章

熱工具

記事本++7.3.1
好用且免費(fèi)的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強(qiáng)大的PHP整合開(kāi)發(fā)環(huán)境

Dreamweaver CS6
視覺(jué)化網(wǎng)頁(yè)開(kāi)發(fā)工具

SublimeText3 Mac版
神級(jí)程式碼編輯軟體(SublimeText3)

熱門(mén)話題

PHP設(shè)置的關(guān)鍵在於明確安裝方式、配置php.ini、連接Web服務(wù)器及啟用必要擴(kuò)展。 1.安裝PHP:Linux用apt、Mac用Homebrew、Windows推薦XAMPP;2.配置php.ini:調(diào)整錯(cuò)誤報(bào)告、上傳限制等並重啟服務(wù)器;3.搭配Web服務(wù)器:Apache通過(guò)mod_php,Nginx使用PHP-FPM;4.安裝常用擴(kuò)展:如mysqli、json、mbstring等以支持完整功能。

註釋不能馬虎是因?yàn)樗忉尨a存在的原因而非功能,例如兼容老接口或第三方限制,否則看代碼的人只能靠猜。必須加註釋的地方包括複雜的條件判斷、特殊的錯(cuò)誤處理邏輯、臨時(shí)繞過(guò)的限制。寫(xiě)註釋更實(shí)用的方法是根據(jù)場(chǎng)景選擇單行註釋或塊註釋?zhuān)瘮?shù)、類(lèi)、文件開(kāi)頭用文檔塊註釋說(shuō)明參數(shù)與返回值,並保持註釋更新,對(duì)複雜邏輯可在前面加一行概括整體意圖,同時(shí)不要用註釋封存代碼而應(yīng)使用版本控制工具。

寫(xiě)好PHP註釋的關(guān)鍵在於明確目的與規(guī)範(fàn),註釋?xiě)?yīng)解釋“為什麼”而非“做了什麼”,避免冗餘或過(guò)於簡(jiǎn)單。 1.使用統(tǒng)一格式,如docblock(/*/)用於類(lèi)、方法說(shuō)明,提升可讀性與工具兼容性;2.強(qiáng)調(diào)邏輯背後的原因,如說(shuō)明為何需手動(dòng)輸出JS跳轉(zhuǎn);3.在復(fù)雜代碼前添加總覽性說(shuō)明,分步驟描述流程,幫助理解整體思路;4.合理使用TODO和FIXME標(biāo)記待辦事項(xiàng)與問(wèn)題,便於後續(xù)追蹤與協(xié)作。好的註釋能降低溝通成本,提升代碼維護(hù)效率。

易於效率,啟動(dòng)啟動(dòng)tingupalocalserverenverenvirestoolslikexamppandacodeeditorlikevscode.1)installxamppforapache,mysql,andphp.2)uscodeeditorforsyntaxssupport.3)

PHPblockcommentsareusefulforwritingmulti-lineexplanations,temporarilydisablingcode,andgeneratingdocumentation.Theyshouldnotbenestedorleftunclosed.BlockcommentshelpindocumentingfunctionswithPHPDoc,whichtoolslikePhpStormuseforauto-completionanderrorche

ToinstallPHPquickly,useXAMPPonWindowsorHomebrewonmacOS.1.OnWindows,downloadandinstallXAMPP,selectcomponents,startApache,andplacefilesinhtdocs.2.Alternatively,manuallyinstallPHPfromphp.netandsetupaserverlikeApache.3.OnmacOS,installHomebrew,thenrun'bre

寫(xiě)好註釋的關(guān)鍵在於說(shuō)明“為什麼”而非僅“做了什麼”,提升代碼可讀性。 1.註釋?xiě)?yīng)解釋邏輯原因,例如值選擇或處理方式背後的考量;2.對(duì)複雜邏輯使用段落式註釋?zhuān)爬ê瘮?shù)或算法的整體思路;3.定期維護(hù)註釋確保與代碼一致,避免誤導(dǎo),必要時(shí)刪除過(guò)時(shí)內(nèi)容;4.在審查代碼時(shí)同步檢查註釋?zhuān)瑏K通過(guò)文檔記錄公共邏輯以減少代碼註釋負(fù)擔(dān)。

PHP註釋代碼常用方法有三種:1.單行註釋用//或#屏蔽一行代碼,推薦使用//;2.多行註釋用/.../包裹代碼塊,不可嵌套但可跨行;3.組合技巧註釋如用/if(){}/控制邏輯塊,或配合編輯器快捷鍵提升效率,使用時(shí)需注意閉合符號(hào)和避免嵌套。
