萬盛學電腦網

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

PHP 協程與生成器實作合作式多任務調度器

背景:生成器

PHP 5.5 引入 yield 關鍵字,函數可成為 生成器,回傳 Generator 物件 (實作 Iterator),支援惰性產出值,不一次載入全部資料到記憶體。

<?php
function xrange($start, $end, $step = 1) {
    for ($i = $start; $i <= $end; $i += $step) {
        yield $i; // 暫停並產出值
    }
}

foreach (xrange(1, 1_000_000) as $num) {
    echo $num, "\n"; // 只佔用常數記憶體
}
?>

從生成器到協程

yield 可作為 表達式 接收外部傳入的值 (send()),形成雙向通訊,這就是 協程。

<?php
function logger($file) {
    $fp = fopen($file, 'a');
    while (true) {
        fwrite($fp, yield . "\n"); // 接收 send() 傳入的值並寫入
    }
}

$log = logger(__DIR__ . '/app.log');
$log->send('First message');
$log->send('Second message');
?>

合作式多任務調度器

利用 yield 主動讓出控制權,調度器輪詢任務隊列,實現單執行緒「並發」。

<?php
class Task {
    public $taskId;
    private $coroutine;
    private $sendValue = null;
    private $beforeFirstYield = true;

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

    public function getTaskId() { return $this->taskId; }
    public function setSendValue($v) { $this->sendValue = $v; }

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

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

class Scheduler {
    private $taskQueue = []; // SplQueue
    private $taskIdCounter = 0;

    public function newTask(Generator $coroutine) {
        $taskId = ++$this->taskIdCounter;
        $task = new Task($taskId, $coroutine);
        $this->taskQueue[$taskId] = $task;
        return $taskId;
    }

    public function run() {
        while ($this->taskQueue) {
            foreach ($this->taskQueue as $id => $task) {
                if ($task->isFinished()) {
                    unset($this->taskQueue[$id]);
                    continue;
                }
                $task->run(); // 執行到下一個 yield
            }
        }
    }
}

// 範例任務
function taskA() {
    for ($i = 1; $i <= 3; $i++) {
        echo "Task A: $i\n";
        yield; // 讓出控制權
    }
}
function taskB() {
    for ($i = 1; $i <= 3; $i++) {
        echo "Task B: $i\n";
        yield;
    }
}

$scheduler = new Scheduler();
$scheduler->newTask(taskA());
$scheduler->newTask(taskB());
$scheduler->run();
/*
輸出交錯:
Task A: 1
Task B: 1
Task A: 2
Task B: 2
Task A: 3
Task B: 3
*/
?>

關鍵點

  • yield 是協作式多任務的「讓出點」。
  • 調度器單執行緒輪詢,無競態條件,無需鎖。
  • 適用於 I/O 密集型任務 (HTTP 請求、資料庫查詢、檔案讀寫) 可搭配非阻塞 I/O (stream_select、uv、ReactPHP、Swoole) 發揮最大效益。
  • PHP 8.1+ 引入 Fiber 類別,提供更底層、標準化的協程支援,建議新專案直接使用 Fiber 或成熟框架。
copyright © 萬盛學電腦網 all rights reserved