新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
PHP8.1Fiber交叉執(zhí)行多任務(wù)(附代碼詳解)

拿平時(shí)大家寫的 for 循環(huán)舉例。像 go 你可以寫兩個(gè) go 每個(gè)里面各寫一個(gè)循環(huán)同時(shí)輸入,你可以看到輸出是交替。在過去的php版本中,如果只開啟一個(gè) cli 寫多個(gè) for 循環(huán),那么他的輸出一定是順序的。無法做到交叉輸出(也就是無法在第一個(gè)循環(huán)中執(zhí)行若干次后,讓b再執(zhí)行,b執(zhí)行一段時(shí)間后,再讓A執(zhí)行)。
現(xiàn)在借助 fiber 我們也可以實(shí)現(xiàn)這種操作?!就扑]學(xué)習(xí):PHP視頻教程】
下面這段代碼就可以做到兩個(gè)循環(huán)交叉執(zhí)行。甚至可以控制兩個(gè)程序執(zhí)行的頻率(比如A執(zhí)行3次,B執(zhí)行一次這樣分配)
1) {
if ($startTag) foreach ($reg as $pI) {
$pI->start();
$startTag = false;
}
foreach ($reg as $pI) {
$pI->resume();
}
if ($t1 === true && $t2 === true) {
break;
}
}
1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9
你甚至可以控制兩個(gè)循環(huán)的執(zhí)行頻率,比如 第一個(gè)循環(huán) 執(zhí)行3次后,第二個(gè)循環(huán)執(zhí)行一次。代碼如下
0) {
if ($startTag) foreach ($reg as $pI) {
$pI->start();
$startTag = false;
}
foreach ($reg as $pI) {
$pI->resume();
}
}
1:1 1:2 1:3 2:1 1:4 1:5 1:6 2:2 1:7 1:8 1:9 2:3 2:4 2:5 2:6 2:7 2:8 2:9
addArgument('arg1', InputArgument::OPTIONAL, 'Argument description')
->addOption('option1', null, InputOption::VALUE_NONE, 'Option description');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$t1 = false;
$t2 = false;
$reg = [];
$fId = 1;
$reg[] = new \Fiber(function () use ($fId) {
for ($i = 1; $i < 10; $i++) {
echo $fId . ':' . $i;
echo PHP_EOL;
if ($i % 3 == 0) {
\Fiber::suspend(new SuspendData(Status::Running));
}
}
\Fiber::suspend(new SuspendData(Status::Stop));
});
$fId++;
$reg[] = new \Fiber(function () use ($fId) {
for ($i = 1; $i < 10; $i++) {
echo $fId . ':' . $i;
echo PHP_EOL;
\Fiber::suspend(new SuspendData(Status::Running));
}
\Fiber::suspend(new SuspendData(Status::Stop));
});
$startTag = true;
while (count($reg) > 0) {
if ($startTag) foreach ($reg as $pI) {
$pI->start();
$startTag = false;
}
foreach ($reg as $key => $pI) {
$r = $pI->resume();
if ($r->status === Status::Stop) {
unset($reg[$key]);
}
}
}
return Command::SUCCESS;
}
}
class SuspendData
{
public readonly Status $status;
public function __construct($status)
{
$this->status = $status;
}
}
enum Status
{
case Stop;
case Running;
} 本文題目:PHP8.1Fiber交叉執(zhí)行多任務(wù)(附代碼詳解)
文章來源:http://www.5511xx.com/article/dpscjeo.html


咨詢
建站咨詢
