PHP編程中嘗試程序并發(fā)的幾種方式總結(jié)
本文大約總結(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.dhdzp.com/');
$ch_2 = curl_init('http://www.dhdzp.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.dhdzp.com\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.dhdzp.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如何解決網(wǎng)站大流量與高并發(fā)的問(wèn)題
- php解決搶購(gòu)秒殺抽獎(jiǎng)等大流量并發(fā)入庫(kù)導(dǎo)致的庫(kù)存負(fù)數(shù)的問(wèn)題
- php并發(fā)對(duì)MYSQL造成壓力的解決方法
- php中并發(fā)讀寫(xiě)文件沖突的解決方案
- php并發(fā)加鎖示例
- php多線程并發(fā)實(shí)現(xiàn)方法
- php session的鎖和并發(fā)
- PHP接口并發(fā)測(cè)試的方法(推薦)
- 淺析PHP中Session可能會(huì)引起并發(fā)問(wèn)題
- php使用curl并發(fā)減少后端訪問(wèn)時(shí)間的方法分析
- PHP開(kāi)發(fā)中解決并發(fā)問(wèn)題的幾種實(shí)現(xiàn)方法分析
相關(guān)文章
php類(lèi)自動(dòng)加載器實(shí)現(xiàn)方法
這篇文章主要介紹了php類(lèi)自動(dòng)加載器實(shí)現(xiàn)方法,涉及php針對(duì)文件的讀取、判斷及字符串操作的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-07-07
PHP中sleep()函數(shù)的實(shí)用場(chǎng)景以及注意事項(xiàng)
sleep()函數(shù)是PHP中的一個(gè)休眠函數(shù),可以讓程序在指定的時(shí)間內(nèi)暫停執(zhí)行,以達(dá)到延遲執(zhí)行的效果,本文介紹使用sleep()函數(shù)的實(shí)用場(chǎng)景以及注意事項(xiàng)2023-09-09
PHP計(jì)算數(shù)組中值的和與乘積的方法(array_sum與array_product函數(shù))
這篇文章主要介紹了PHP計(jì)算數(shù)組中值的和與乘積的方法,結(jié)合實(shí)例形式較為詳細(xì)的分析了array_sum與array_product函數(shù)的功能與使用方法,需要的朋友可以參考下2016-04-04
PHP生成驗(yàn)證碼時(shí)“圖像因其本身有錯(cuò)無(wú)法顯示”的解決方法
以下是對(duì)PHP生成驗(yàn)證碼時(shí)“圖像因其本身有錯(cuò)無(wú)法顯示”的解決方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友可以過(guò)來(lái)參考下2013-08-08
file_get_contents("php://input", "r")實(shí)例介
本篇文章是對(duì)file_get_contents("php://input", "r")的實(shí)例進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-07-07
PHP中調(diào)用C/C++制作的動(dòng)態(tài)鏈接庫(kù)的教程
這篇文章主要介紹了PHP中調(diào)用C/C++制作的動(dòng)態(tài)鏈接庫(kù)的教程,文中還簡(jiǎn)單地提到了gcc編譯器下動(dòng)態(tài)鏈接庫(kù)的制作方法,需要的朋友可以參考下2016-03-03

