• Stars
    star
    238
  • Rank 163,123 (Top 4 %)
  • Language
    Assembly
  • License
    Other
  • Created over 3 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

PHP Fiber extension

Fiber Extension

Fiber implementation for PHP using native C fibers.

Warning
Please upgrade to PHP 8.1 instead of using this extension. There are subtle differences, which can't be fixed in the extension.

Requirements

  • PHP 8.0 only (PHP 8.1+ includes Fibers, so this extension is unnecessary)

Installation

Installation of the extension is similar to other PHP extensions.

git clone https://github.com/amphp/ext-fiber
cd ext-fiber
phpize
./configure
make
make test
make install

API

Fibers are made by creating an instance of the Fiber class.

final class Fiber
{
    /**
     * @param callable $callback Function to invoke when starting the fiber.
     */
    public function __construct(callable $callback) {}

    /**
     * Starts execution of the fiber. Returns when the fiber suspends or terminates.
     *
     * @param mixed ...$args Arguments passed to fiber function.
     *
     * @return mixed Value from the first suspension point or NULL if the fiber returns.
     *
     * @throw FiberError If the fiber has already been started.
     * @throw Throwable If the fiber callable throws an uncaught exception.
     */
    public function start(mixed ...$args): mixed {}

    /**
     * Resumes the fiber, returning the given value from {@see Fiber::suspend()}.
     * Returns when the fiber suspends or terminates.
     *
     * @param mixed $value
     *
     * @return mixed Value from the next suspension point or NULL if the fiber returns.
     *
     * @throw FiberError If the fiber has not started, is running, or has terminated.
     * @throw Throwable If the fiber callable throws an uncaught exception.
     */
    public function resume(mixed $value = null): mixed {}

    /**
     * Throws the given exception into the fiber from {@see Fiber::suspend()}.
     * Returns when the fiber suspends or terminates.
     *
     * @param Throwable $exception
     *
     * @return mixed Value from the next suspension point or NULL if the fiber returns.
     *
     * @throw FiberError If the fiber has not started, is running, or has terminated.
     * @throw Throwable If the fiber callable throws an uncaught exception.
     */
    public function throw(Throwable $exception): mixed {}

    /**
     * @return bool True if the fiber has been started.
     */
    public function isStarted(): bool {}

    /**
     * @return bool True if the fiber is suspended.
     */
    public function isSuspended(): bool {}

    /**
     * @return bool True if the fiber is currently running.
     */
    public function isRunning(): bool {}

    /**
     * @return bool True if the fiber has completed execution (returned or threw).
     */
    public function isTerminated(): bool {}

    /**
     * @return mixed Return value of the fiber callback. NULL is returned if the fiber does not have a return statement.
     *
     * @throws FiberError If the fiber has not terminated or the fiber threw an exception.
     */
    public function getReturn(): mixed {}

    /**
     * @return self|null Returns the currently executing fiber instance or NULL if in {main}.
     */
    public static function getCurrent(): ?self {}

    /**
     * Suspend execution of the fiber. The fiber may be resumed with {@see Fiber::resume()} or {@see Fiber::throw()}.
     *
     * Cannot be called from {main}.
     *
     * @param mixed $value Value to return from {@see Fiber::resume()} or {@see Fiber::throw()}.
     *
     * @return mixed Value provided to {@see Fiber::resume()}.
     *
     * @throws FiberError Thrown if not within a fiber (i.e., if called from {main}).
     * @throws Throwable Exception provided to {@see Fiber::throw()}.
     */
    public static function suspend(mixed $value = null): mixed {}
}

A Fiber object is created using new Fiber(callable $callback) with any callable. The callable need not call Fiber::suspend() directly, it may be in a deeply nested call, far down the call stack (or perhaps never call Fiber::suspend() at all). The returned Fiber may be started using Fiber->start(mixed ...$args) with a variadic argument list that is provided as arguments to the callable used when creating the Fiber.

Fiber::suspend() suspends execution of the current fiber and returns execution to the call to Fiber->start(), Fiber->resume(), or Fiber->throw(). The value passed to Fiber::suspend() is used as the return value of these methods. If the fiber throws an exception, the exception is thrown from the call to these methods. Fiber::suspend() will throw an instance of FiberError if called outside a fiber (i.e., if called from {main}).

A suspended fiber may be resumed in one of two ways:

  • returning a value from Fiber::suspend() using Fiber->resume()
  • throwing an exception from Fiber::suspend() using Fiber->throw()

Fiber->getReturn() returns the value returned from a terminated fiber (NULL is returned if the fiber did not return a value). This function will throw an instance of FiberError if the fiber has not completed execution or threw an exception.

Fiber::getCurrent() returns the currently executing Fiber instance or NULL if called from {main}. This allows a fiber to store a reference to itself elsewhere, such as within an event loop callback or an array of awaiting fibers.


ReflectionFiber

ReflectionFiber is used to inspect executing fibers. A ReflectionFiber object can be created from any Fiber object, even if it has not been started or if it has been finished. This reflection class is similar to ReflectionGenerator.

final class ReflectionFiber
{
    /**
     * @param Fiber $fiber Any Fiber object, including those that are not started or have
     *                     terminated.
     */
    public function __construct(Fiber $fiber) {}

    /**
     * @return Fiber The reflected Fiber object.
     */
    public function getFiber(): Fiber {}

    /**
     * @return string Current file of fiber execution.
     *
     * @throws Error If the fiber has not been started or has terminated.
     */
    public function getExecutingFile(): string {}

    /**
     * @return int Current line of fiber execution.
     *
     * @throws Error If the fiber has not been started or has terminated.
     */
    public function getExecutingLine(): int {}

    /**
     * @param int $options Same flags as {@see debug_backtrace()}.
     *
     * @return array Fiber backtrace, similar to {@see debug_backtrace()}
     *               and {@see ReflectionGenerator::getTrace()}.
     *
     * @throws Error If the fiber has not been started or has terminated.
     */
    public function getTrace(int $options = DEBUG_BACKTRACE_PROVIDE_OBJECT): array {}

    /**
     * @return callable Callable used to create the fiber.
     *
     * @throws Error If the fiber has been terminated.
     */
    public function getCallable(): callable {}
}

Unfinished Fibers

Fibers that are not finished (do not complete execution) are destroyed similarly to unfinished generators, executing any pending finally blocks. Fiber::suspend() may not be invoked in a force-closed fiber, just as yield cannot be used in a force-closed generator. Fibers are destroyed when there are no references to the Fiber object.

Fiber Stacks

Each fiber is allocated a separate C stack and VM stack on the heap. The C stack is allocated using mmap if available, meaning physical memory is used only on demand (if it needs to be allocated to a stack value) on most platforms. Each fiber stack is allocated a maximum of 8M of memory by default, settable with an ini setting fiber.stack_size. Note that this memory is used for the C stack and is not related to the memory available to PHP code. VM stacks for each fiber are allocated in a similar way to generators and use a similar amount of memory and CPU. VM stacks are able to grow dynamically, so only a single VM page (4K) is initially allocated.

PHP 8.1+

This extension only works with PHP 8.0. The Fiber RFC was accepted and will be a part of PHP 8.1, so this extension is not necessary and incompatible with PHP 8.1 and above.

More Repositories

1

amp

A non-blocking concurrency framework for PHP applications. 🐘
PHP
4,135
star
2

http-server

An advanced async HTTP server library for PHP, perfect for real-time apps and APIs with high concurrency demands.
PHP
1,276
star
3

parallel

An advanced parallelization library for PHP, enabling efficient multitasking, optimizing resource use, and application responsiveness through multiple CPU threads.
PHP
745
star
4

http-client

An advanced async HTTP client library for PHP, enabling efficient, non-blocking, and concurrent requests and responses.
PHP
695
star
5

byte-stream

A non-blocking stream abstraction for PHP based on Amp.
PHP
357
star
6

mysql

An async MySQL client for PHP, optimizing database interactions with efficient non-blocking capabilities. Perfect for responsive, high-performance applications.
PHP
346
star
7

thread

Unmaintained. Use https://github.com/amphp/parallel.
PHP
297
star
8

parallel-functions

Simplified parallel processing for PHP based on Amp.
PHP
264
star
9

process

An async process dispatcher for Amp.
PHP
225
star
10

socket

Non-blocking socket and TLS functionality for PHP based on Amp.
PHP
214
star
11

ext-uv

C
186
star
12

sync

Non-blocking synchronization primitives for PHP based on Amp and Revolt.
PHP
155
star
13

dns

Async DNS resolution for PHP based on Amp.
PHP
149
star
14

redis

Efficient asynchronous communication with Redis servers, enabling scalable and responsive data storage and retrieval.
PHP
146
star
15

websocket-client

Async WebSocket client for PHP based on Amp.
PHP
138
star
16

parser

A generator parser to make streaming parsers simple.
PHP
121
star
17

websocket-server

WebSocket component for PHP based on the Amp HTTP server.
PHP
112
star
18

serialization

Serialization tools for IPC and data storage in PHP.
PHP
105
star
19

cache

A fiber-aware cache API based on Amp and Revolt.
PHP
95
star
20

windows-registry

Windows Registry Reader.
PHP
92
star
21

file

An abstraction layer and non-blocking file access solution that keeps your application responsive.
PHP
90
star
22

hpack

HPack - HTTP/2 header compression implementation in PHP.
PHP
90
star
23

postgres

Async Postgres client for PHP based on Amp.
PHP
88
star
24

http

HTTP primitives which can be shared by servers and clients.
PHP
87
star
25

beanstalk

Asynchronous Beanstalk Client for PHP.
PHP
63
star
26

cluster

Building multi-core network applications with PHP.
PHP
56
star
27

aerys

A non-blocking HTTP application, WebSocket and file server for PHP based on Amp.
PHP
52
star
28

pipeline

Concurrent iterators and pipeline operations.
PHP
43
star
29

http-server-router

A router for Amp's HTTP Server.
PHP
37
star
30

green-thread

PHP
37
star
31

getting-started

A getting started guide for Amp.
PHP
36
star
32

websocket

Shared code for websocket servers and clients.
PHP
34
star
33

ssh

Async SSH client for PHP based on Amp.
PHP
33
star
34

injector

A recursive dependency injector used to bootstrap and wire together S.O.L.I.D., object-oriented PHP applications.
PHP
32
star
35

log

Non-blocking logging for PHP based on Amp and Monolog.
PHP
31
star
36

uri

Uri Parser and Resolver.
PHP
24
star
37

amphp.github.io

Main website repository.
HTML
23
star
38

react-adapter

Makes any ReactPHP library compatible with Amp.
PHP
23
star
39

artax

An async HTTP/1.1 client for PHP based on Amp.
PHP
21
star
40

phpunit-util

Helper package to ease testing with PHPUnit.
PHP
21
star
41

http-server-static-content

An HTTP server plugin to serve static files like HTML, CSS, JavaScript, and images effortlessly.
PHP
21
star
42

http-server-session

An HTTP server plugin that simplifies session management for your applications. Effortlessly handle user sessions, securely managing data across requests.
PHP
17
star
43

mysql-dbal

PHP
16
star
44

http-server-form-parser

An HTTP server plugin that simplifies form data handling. Effortlessly parse incoming form submissions and extracting its data.
HTML
16
star
45

stomp

A non-blocking STOMP client built on the amp concurrency framework
PHP
15
star
46

aerys-reverse

Reverse HTTP proxy handler for Aerys
PHP
15
star
47

sql

Common interfaces for Amp based SQL drivers.
PHP
14
star
48

loop

Discontinued. Merged into https://github.com/amphp/amp.
PHP
12
star
49

http-tunnel

This package provides an HTTP CONNECT tunnel for PHP based on Amp.
PHP
11
star
50

http-client-cookies

Automatic cookie handling for Amp's HTTP client.
PHP
10
star
51

rpc

Remote procedure calls for PHP based on Amp.
PHP
9
star
52

http-client-psr7

PSR-7 adapter for amphp/http-client.
PHP
8
star
53

http-client-cache

An async HTTP cache for Amp's HTTP client.
PHP
7
star
54

sql-common

Implementations shared by amphp/postgres and amphp/mysql
PHP
7
star
55

php-cs-fixer-config

Common code style configuration for all @amphp projects.
PHP
6
star
56

react-stream-adapter

Adapters to make React's and Amp's streams compatible.
PHP
6
star
57

windows-process-wrapper

Child process wrapper to support non-blocking process pipes on Windows.
C
5
star
58

amphp.org

Documentation for AMPHP v3 based libraries.
HTML
5
star
59

quic

PHP
4
star
60

logo

Repository to store the logo and other assets.
3
star
61

dbus

A non-blocking DBus Connector with message serialization based on Amp.
PHP
2
star
62

website-tools

Website administration tools for amphp.org.
PHP
1
star
63

template

This repository serves as template for new amphp projects.
1
star
64

website-shared

Unmaintained. Has been merged into https://github.com/amphp/amphp.github.io.
1
star
65

.github

1
star