纤程 用一个异常来恢复 fiber 的执行

PHP: 纤程 - Manual https://www.php.net/manual/zh/language.fibers.php

PHP: Fibers - Manual https://www.php.net/manual/en/language.fibers.php

Fibers ¶

Fibers overview ¶

(PHP 8 >= 8.1.0)

Fibers represent full-stack, interruptible functions. Fibers may be suspended from anywhere in the call-stack, pausing execution within the fiber until the fiber is resumed at a later time.

Fibers pause the entire execution stack, so the direct caller of the function does not need to change how it invokes the function.

Execution may be interrupted anywhere in the call stack using Fiber::suspend() (that is, the call to Fiber::suspend() may be in a deeply nested function or not even exist at all).

Unlike stack-less Generators, each Fiber has its own call stack, allowing them to be paused within deeply nested function calls. A function declaring an interruption point (that is, calling Fiber::suspend()) need not change its return type, unlike a function using yield which must return a Generator instance.

Fibers can be suspended in any function call, including those called from within the PHP VM, such as functions provided to array_map() or methods called by foreach on an Iterator object.

Once suspended, execution of the fiber may be resumed with any value using Fiber::resume() or by throwing an exception into the fiber using Fiber::throw(). The value is returned (or exception thrown) from Fiber::suspend().

Note: Due to current limitations it is not possible to switch fibers in the destructor of an object.

Example #1 Basic usage

<?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');
?>

The above example will output:

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

 

纤程概述 ¶

(PHP 8 >= 8.1.0)

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

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

你可以在调用堆栈的任意地方使用 Fiber::suspend() 中断执行(也就是说,Fiber::suspend() 的调用位置可以在一个深度嵌套的函数中,甚至可以不存在)。

与无栈的 Generator 不同, 每一个 Fiber 拥有自己的调用栈,并允许在一个深度前度的函数调用中将它们暂停。 声明了中断(interruption)点的函数(即调用 Fiber::suspend()) 不需要改变自己的返回类型,不像使用 yield 一样需要返回一个 Generator 实例。

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

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

注意: 由于当前限制,不能在对象的析构函数中打开或关闭纤程。

 

 PHP: Fiber - Manual https://www.php.net/manual/zh/class.fiber.php

 

 

posted @ 2023-10-30 12:13  papering  阅读(41)  评论(0编辑  收藏  举报