您好,登錄后才能下訂單哦!
怎么在PHP中實現一個協程任務調度demo?相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
一、phpStudy,是一個新手入門最常用的開發環境。二、WampServer,WampServer也同樣的也是和phpStudy一樣操作簡單對小白比較友好。三、XAMPP,XAMPP(Apache+MySQL+PHP+PERL)是一個功能強大的建站集成軟件包;四、MAMP,MAMP分為兩種MAMP和MAMP Pro for Mac。五、寶塔面板,寶塔面板是一款服務器管理軟件,支持windows和linux系統。六、UPUPW,UPUPW是目前Windows平臺下最具特色的Web服務器PHP套件。
具體如下:
<?php class Task { protected $taskId; protected $coroutine; protected $sendValue = null; protected $beforeFirstYield = true; public function __construct($taskId, Generator $coroutine) { $this->taskId = $taskId; $this->coroutine = $coroutine; } public function getTaskId() { return $this->taskId; } public function setSendValue($sendValue) { $this->sendValue = $sendValue; } public function run() { if ($this->beforeFirstYield) { $this->beforeFirstYield = false; return $this->coroutine->current(); } else { $retval = $this->coroutine->send($this->sendValue); $this->sendValue = null; return $retval; } } public function isFinished() { return !$this->coroutine->valid(); } } class Scheduler { protected $maxTaskId = 0; protected $taskMap = []; // taskId => task protected $taskQueue; public function __construct() { $this->taskQueue = new SplQueue(); } public function newTask(Generator $coroutine) { $tid = ++$this->maxTaskId; $task = new Task($tid, $coroutine); $this->taskMap[$tid] = $task; $this->schedule($task); return $tid; } public function schedule(Task $task) { $this->taskQueue->enqueue($task); } public function run() { while (!$this->taskQueue->isEmpty()) { $task = $this->taskQueue->dequeue(); $task->run(); if ($task->isFinished()) { unset($this->taskMap[$task->getTaskId()]); } else { $this->schedule($task); } } } } function task1() { for ($i = 1; $i <= 10; ++$i) { echo "This is task 1 iteration $i.\n"; sleep(1); yield; } } function task2() { for ($i = 1; $i <= 10; ++$i) { echo "This is task 2 iteration $i.\n"; sleep(1); yield; } } $scheduler = new Scheduler; $scheduler->newTask(task1()); $scheduler->newTask(task2()); $scheduler->run();
運行結果:
This is task 1 iteration 1.
This is task 1 iteration 2.
This is task 1 iteration 3.
This is task 1 iteration 4.
This is task 1 iteration 5.
This is task 1 iteration 6.
This is task 1 iteration 7.
This is task 1 iteration 8.
This is task 1 iteration 9.
This is task 1 iteration 10.
看完上述內容,你們掌握怎么在PHP中實現一個協程任務調度demo的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。