使用 php 和 pthreads 或其他库的 sql 查询的多线程
Multithreading with sql query using php and pthreads or other library
我想在拍卖会上模拟出价,1秒内大概有30个出价。但是我不知道, class 我必须使用什么?可堆叠还是泳池?我用 https://github.com/krakjoe/pthreads.
您想使用stream_socket_client
这几乎是 PHP 所能达到的最接近多线程的程度。它可以处理 30 个连接,并且能够 return 每个套接字上的结果。
创建出价
$bids[] = 'makebid/item8349/?bid=1.00';
$bids[] = 'makebid/item8350/?bid=1.50';
创建 "processes":
$timeout = 20;
$result = array();
$sockets = array();
$buffer_size = 8192;
$id = 0;
foreach($bids as $bid){
$stream = stream_socket_client("auction.com:80", $errno,$errstr, $timeout,
STREAM_CLIENT_ASYNC_CONNECT|STREAM_CLIENT_CONNECT);
if ($stream) {
$sockets[$id++] = $stream; // supports multiple sockets
$http = "GET /$bid HTTP/1.0\r\nHost: auction.com\r\n\r\n";
fwrite($stream, $http);
}
else {
echo "$id Failed\n";
}
}
监控出价:
while (count($sockets)) {
$read = $sockets;
stream_select($read, $write = NULL, $except = NULL, $timeout);
if (count($read)) {
foreach ($read as $r) {
$id = array_search($r, $sockets);
$data = fread($r, $buffer_size);
if (strlen($data) == 0) {
echo "$id Closed: " . date('h:i:s') . "\n\n\n";
fclose($r);
unset($sockets[$id]);
}
else {
$result[$id] .= $data;
}
}
}
else {
echo 'Timeout: ' . date('h:i:s') . "\n\n\n";
break;
}
}
我想在拍卖会上模拟出价,1秒内大概有30个出价。但是我不知道, class 我必须使用什么?可堆叠还是泳池?我用 https://github.com/krakjoe/pthreads.
您想使用stream_socket_client
这几乎是 PHP 所能达到的最接近多线程的程度。它可以处理 30 个连接,并且能够 return 每个套接字上的结果。
创建出价
$bids[] = 'makebid/item8349/?bid=1.00';
$bids[] = 'makebid/item8350/?bid=1.50';
创建 "processes":
$timeout = 20;
$result = array();
$sockets = array();
$buffer_size = 8192;
$id = 0;
foreach($bids as $bid){
$stream = stream_socket_client("auction.com:80", $errno,$errstr, $timeout,
STREAM_CLIENT_ASYNC_CONNECT|STREAM_CLIENT_CONNECT);
if ($stream) {
$sockets[$id++] = $stream; // supports multiple sockets
$http = "GET /$bid HTTP/1.0\r\nHost: auction.com\r\n\r\n";
fwrite($stream, $http);
}
else {
echo "$id Failed\n";
}
}
监控出价:
while (count($sockets)) {
$read = $sockets;
stream_select($read, $write = NULL, $except = NULL, $timeout);
if (count($read)) {
foreach ($read as $r) {
$id = array_search($r, $sockets);
$data = fread($r, $buffer_size);
if (strlen($data) == 0) {
echo "$id Closed: " . date('h:i:s') . "\n\n\n";
fclose($r);
unset($sockets[$id]);
}
else {
$result[$id] .= $data;
}
}
}
else {
echo 'Timeout: ' . date('h:i:s') . "\n\n\n";
break;
}
}