php 8.6 中 fiber 协程通过 fiber 类的实例化、start() 启动以及 resume() 和 throw() 进行控制,实现用户态的轻量级并发。具体做法是创建一个包含执行逻辑的闭包,实例化 fiber 对象后调用 start() 运行至第一个 fiber::suspend() 点挂起,随后在主流程中通过 resume() 恢复执行并传递值,或通过 throw() 向协程内抛出异常以改变其运行路径。

Fiber::start() 与 Fiber::suspend() 如何配合完成首次挂起与数据交换?
Fiber::start() 会立即在子协程上下文中执行传入的闭包,直到遇到 Fiber::suspend() 方法时暂停执行并返回该方法的参数;主程序通过 resume() 继续执行并再次传递数据给协程。这种机制允许主程序与协程之间进行双向的数据通信,且每次挂起点都可以作为状态保存的锚点。

<?php
$fiber = new Fiber(function ($initial) {
echo "Fiber started with: $initial\n";
// 第一次挂起,返回 'suspended_value' 给主程序
$value = Fiber::suspend('suspended_value');
echo "Resumed with: $value\n";
return 'final_result';
});
// 启动协程,传入初始参数
$result = $fiber->start('init_data');
echo "Main got: $result\n"; // 输出: Main got: suspended_value
// 恢复协程,传入新值
$final = $fiber->resume('new_data');
echo "Final result: $final\n"; // 输出: Final result: final_result
?>
上述代码展示了标准的启动与恢复流程。首先调用 start('init_data'),协程内部打印初始值并在 suspend 处暂停,主程序接收到字符串 'suspended_value'。接着调用 resume('new_data'),协程从挂起点继续,接收到的值赋给变量 $value 并打印,最后协程结束并返回 'final_result'。注意 start() 只能调用一次,后续必须使用 resume() 或 throw()。
立即学习“PHP免费学习笔记(深入)”;
使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。
Fiber::throw() 如何在协程内部处理异常并影响执行流?
Fiber::throw() 用于向当前挂起的协程内部抛出一个异常,该异常会在 Fiber::suspend() 的位置被触发,从而允许协程通过 try-catch 块捕获异常并进行错误处理或清理操作。如果协程未捕获该异常,它将传播回调用 throw() 的主程序,导致主程序也抛出相同的异常。
<?php
$fiber = new Fiber(function () {
try {
echo "Before suspend\n";
Fiber::suspend();
echo "This will not print if exception is thrown\n";
} catch (RuntimeException $e) {
echo "Caught exception in fiber: " . $e->getMessage() . "\n";
return 'handled';
}
});
$fiber->start();
try {
$fiber->throw(new RuntimeException('Error from main'));
} catch (RuntimeException $e) {
echo "Exception propagated to main: " . $e->getMessage() . "\n";
}
?>
在此示例中,协程启动后在 suspend 处挂起。主程序调用 throw(new RuntimeException(...)),异常在协程内部的 suspend 处抛出。由于协程内有 try-catch 块,异常被捕获,打印错误信息并返回 'handled'。若移除 try-catch,则异常将直接传播到主程序的 throw 调用处,导致主程序崩溃或进入其自身的异常处理逻辑。这体现了 throw() 对协程内部状态的强制干预能力。
当协程内部发生未捕获异常时,Fiber::isStarted() 和 Fiber::isRunning() 的状态如何变化?
当协程内部发生未捕获异常时,协程的生命周期立即终止,Fiber::isStarted() 保持为 true(因为已经启动过),但 Fiber::isRunning() 变为 false,且任何后续的 resume() 或 throw() 调用都会抛出 FiberError。此时协程处于不可恢复的死亡状态,必须重新创建新的 Fiber 实例来继续工作。
<?php
$fiber = new Fiber(function () {
throw new LogicException('Fatal error in fiber');
});
$fiber->start();
echo "Is Started: " . ($fiber->isStarted() ? 'true' : 'false') . "\n"; // true
echo "Is Running: " . ($fiber->isRunning() ? 'true' : 'false') . "\n"; // false
try {
$fiber->resume();
} catch (FiberError $e) {
echo "Cannot resume dead fiber: " . $e->getMessage() . "\n";
}
?>
运行此代码,协程在 start() 期间抛出 LogicException,该异常会传播到主程序。主程序需捕获此异常以防止崩溃。检查状态发现 isStarted() 为真,但 isRunning() 为假,表明协程已非正常退出。尝试再次 resume() 会触发 FiberError,证实了协程已彻底销毁,无法复用。这是在使用 Fiber 时必须处理的边界情况,确保在异常发生后及时清理或重建协程资源。


















