Skip to content

[Docs] Provide explanation of the change in mental model between Fibers and the Event Loop #7

Open
@Kingdutch

Description

@Kingdutch

When framework maintainers adopt fibers it's likely that they'll write code along the line of:

// Wrap request handling in a Fiber, this allows us to call the optional
// background task if any code tries to suspend a fiber.
$fiber = new \Fiber(fn() => execute_main_task());
$fiber->start();
while ($fiber->isSuspended()) {
  run_background_task();
  $fiber->resume();
}
// If the fiber isn't suspended, it's either terminated or an exception
// has been thrown, so it should be safe to get the return value without
// explicitly checking \Fiber::isTerminated().
$response = $fiber->getReturn();

This provides a mental model where things should check whether they're in a Fiber before they try to suspend and let other tasks perform some tasks.

In contrast with the event loop we should invert the thinking and schedule the secondary tasks as cancellable items while invoking the main task "synchronously" (in that it can not be inferred in the calling site whether it'll ever suspend). For example using code adjusted from revoltphp/event-loop#91

$cancelled = false;
$callbackId = EventLoop::repeat(0, function (string $callbackId) use (&$cancelled): void {
    EventLoop::disable($callbackId);
    execute_background_task();
    if (!$cancelled) {
        EventLoop::enable($callbackId);
    }
});

$response = execute_main_task();
$cancelled = TRUE;

By providing an explanation of this difference in mental model from "Thinking in suspendable fibers" to "thinking in schedulable tasks" we can help adoption of the Revolt Event Loop for framework maintainers.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions