函式名:Fiber::isStarted()
適用版本:PHP 8.1.0 及以上版本
用法:Fiber::isStarted() 函式用於檢查一個協程是否已經開始執行。
示例:
function myCoroutine() {
echo "Coroutine started\n";
Fiber::yield();
echo "Coroutine resumed\n";
}
$fiber = new Fiber('myCoroutine');
echo "Is fiber started? " . (Fiber::isStarted($fiber) ? "Yes" : "No") . "\n"; // 輸出: Is fiber started? No
$fiber->start();
echo "Is fiber started? " . (Fiber::isStarted($fiber) ? "Yes" : "No") . "\n"; // 輸出: Is fiber started? Yes
$fiber->resume();
在上面的示例中,首先建立了一個名為 myCoroutine
的協程函式。然後,透過 new Fiber('myCoroutine')
建立了一個 Fiber
物件,並將其賦值給變數 $fiber
。接著,透過呼叫 Fiber::isStarted($fiber)
檢查協程是否已經開始執行,此時返回值為 false
,因為協程還未開始。然後,透過呼叫 $fiber->start()
啟動協程,再次呼叫 Fiber::isStarted($fiber)
檢查協程是否已經開始執行,此時返回值為 true
,因為協程已經開始執行。
請注意,Fiber
類是在 PHP 8.1.0 版本中引入的,因此在較舊的 PHP 版本中無法使用該函式。