萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 協程與生成器實現協作式多任務調度器 (上)

背景:從生成器到協程

PHP 5.5 引入生成器,5.7/7.0 完善協程支援。生成器本質是**可中斷函數**,`yield` 既可產出值,也可接收外部傳入值 (`send()`),形成雙向通訊。

生成器基礎

<?php
function xrange(int $start, int $end, int $step = 1): Generator
{
    for ($i = $start; $i <= $end; $i += $step) {
        yield $i;
    }
}

foreach (xrange(1, 5) as $n) {
    echo "$n "; // 1 2 3 4 5
}
// 記憶體常數級,不建立百萬元素陣列
?>

協程雙向通訊

<?php
function logger(string $file): Generator
{
    $fp = fopen($file, 'a');
    while (true) {
        $msg = yield; // 接收外部 send() 的值
        fwrite($fp, date('c') . " $msg\n");
    }
}

$log = logger(__DIR__ . '/app.log');
$log->send('User login');
$log->send('Order created');
// 協程在 yield 處暫停,send() 喚醒並傳值
?>

協作式多任務調度器核心

<?php
class Task
{
    public int $id;
    public Generator $coroutine;
    public mixed $sendValue = null;
    public bool $beforeFirstYield = true;

    public function __construct(int $id, Generator $coroutine)
    {
        $this->id = $id;
        $this->coroutine = $coroutine;
    }

    public function run(): mixed
    {
        if ($this->beforeFirstYield) {
            $this->beforeFirstYield = false;
            return $this->coroutine->current();
        }
        $retval = $this->coroutine->send($this->sendValue);
        $this->sendValue = null;
        return $retval;
    }

    public function isFinished(): bool
    {
        return !$this->coroutine->valid();
    }
}

class Scheduler
{
    private SplQueue $taskQueue;
    private int $tid = 0;

    public function __construct()
    {
        $this->taskQueue = new SplQueue();
    }

    public function newTask(Generator $coroutine): int
    {
        $task = new Task(++$this->tid, $coroutine);
        $this->taskQueue->enqueue($task);
        return $task->id;
    }

    public function run(): void
    {
        while (!$this->taskQueue->isEmpty()) {
            $task = $this->taskQueue->dequeue();
            $task->run();
            if ($task->isFinished()) {
                echo "Task {$task->id} finished\n";
            } else {
                $this->taskQueue->enqueue($task);
            }
        }
    }
}

// 示範任務
function taskA(): Generator
{
    for ($i = 1; $i <= 3; $i++) {
        echo "A$i ";
        yield;
    }
}
function taskB(): Generator
{
    for ($i = 1; $i <= 2; $i++) {
        echo "B$i ";
        yield;
    }
}

$scheduler = new Scheduler();
$scheduler->newTask(taskA());
$scheduler->newTask(taskB());
$scheduler->run();
// 輸出: A1 B1 A2 B2 A3
?>

關鍵概念總結

  • Task:封裝 Generator,管理 ID、send 值、執行狀態
  • Scheduler:任務隊列,輪詢調度 `run()`,實現時間片輪轉
  • yield:主動讓出控制權,切換至下一任務
  • send():向協程傳遞資料,實現任務間通訊

下篇將介紹非阻塞 I/O 整合、Promise/Deferred 模式、實際網路請求協程化與 ReactPHP/Amp 整合。

copyright © 萬盛學電腦網 all rights reserved