编程

PHP 8.1 新特性:纤程 Fiber 类

1933 2021-12-29 09:21:16

介绍

纤程(Fiber)代表了有完整栈、可中断的功能。Fiber 可以从调用堆栈中的任何位置挂起,在 Fiber 内暂停执行,直到稍后恢复 Fiber。

类摘要

final class Fiber {
	/* 方法 */
	public __construct(callable $callback)
	public start(mixed ...$args): mixed
	public resume(mixed $value = null): mixed
	public throw(Throwable $exception): mixed
	public getReturn(): mixed
	public isStarted(): bool
	public isSuspended(): bool
	public isRunning(): bool
	public isTerminated(): bool
	public static suspend(mixed $value = null): mixed
	public static getCurrent(): ?Fiber
}

纤程概要

(PHP 8 >= 8.1.0)

纤程(Fiber)表示一组有完整栈、可中断的功能。 纤程可以在调用堆栈中的任何位置被挂起,在纤程内暂停执行,直到稍后恢复。

纤程可以暂停整个执行栈,因此该函数的直接调用者不需要改变该函数的执行方式。

可以在任何地方使用 Fiber::suspend() 调用栈中断执行(也就是说,Fiber::suspend() 的调用可以在一个深度嵌套的函数中调用,即使它不存在)。

不像没有栈的生成器,每个 Fiber 有它自己的调用栈,允许它们在深度嵌套函数调用中暂停。一个函数声明一个中断点(即, 调用 Fiber::suspends())不需要改变他的返回类型,而不像使用 yield 的函数,必须返回 Generator 实例。

纤程可以在任何函数调用中暂停,包括那些在 PHP VM 中被调用的函数,比如用于 array_map() 的函数或者提供 Iterator 实例以被 foreach 调用的方法。

纤程一旦被暂停,可以使用 Fiber::resume() 传递任意值、或者使用 Fiber::throw() 向纤程抛出一个异常以恢复运行。这个值或者异常将会在 Fiber::suspend() 中被返回(抛出)。

示例:

<?php
$fiber = new Fiber(function (): void {
   $value = Fiber::suspend('fiber');
   echo "Value used to resume fiber: ", $value, PHP_EOL;
});

$value = $fiber->start();

echo "Value from fiber suspending: ", $value, PHP_EOL;

$fiber->resume('test');
?>

输出:

Value from fiber suspending: fiber
Value used to resume fiber: test

目录