pcntl 介绍
pcntl扩展可以支持 PHP 的多线程操作。详细扩展安装可以自行百度。
$request = [
[‘param1’ => 1,],
[‘param1’ => 2,],
[‘param1’ => 3,],
];master($ids);
示例代码:
/**
* 开启多个进程
*
* @param $requests
*/
function master($requests)
{
$list = [];
$start = microtime(true);
cronOutlog(“All request handle start at ” . $start . PHP_EOL);
foreach ($requests as $request)
{
$pid = worker($request);
if (!$pid)
{
cronOutlog(‘handle fail!’ . PHP_EOL);
return;
}
array_push($list, $pid);
}
while (count($list) > 0)
{
foreach ($list as $k => $pid)
{
$res = pcntl_waitpid($pid, $status, WNOHANG);
if ($res == – 1 || $res > 0)
{
unset($list[$k]);
}
}
usleep(100);
}
$end = microtime(true);
$cost = $end – $start;
cronOutlog(“All request handle stop at ” . $end . “\t cost:” . $cost . PHP_EOL);
}
/**
* 单个进程处理
*
* @param $request
*
* @return bool|int
*/
function worker($request)
{
global $neo;
$pid = pcntl_fork();
if ($pid == – 1)
{
return false;
}
if ($pid > 0)
{
return $pid;
}
if ($pid == 0)
{
$start = microtime(true);
cronOutlog(getmypid() . “\t start ” . $start . PHP_EOL);
$url = “”;//指定网址
$param1 = $request[‘param1’];//指定参数
$response = sendHttpRequest($url, [‘param1’ => $param1]);
//sleep($time);
cronOutlog(getmypid() . ” response:” . json_encode($response));
// echo getmypid() .”\n”;
$end = microtime(true);
$cost = $end – $start;
cronOutlog(getmypid() . “\t stop ” . $end . “\tcost:” . $cost . PHP_EOL);
exit(0);
}
}
执行结果示例:
感兴趣的同学可以试试哦。
转载请注明:苏demo的别样人生 » php pcntl多线程请求网址及传参示例