Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Kingdutch opened this issue Mar 17, 2024 · 1 comment

Comments

@Kingdutch
Copy link

Kingdutch commented Mar 17, 2024

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.

@kelunik
Copy link
Member

kelunik commented Apr 4, 2024

Generally, there's no need to construct a fiber instance manually. There's no concept of background tasks in co-operative scheduling. repeat(0) will hog the CPU.

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.

Users should generally think in fibers and don't worry about scheduling too much.

I have some idea what you're trying to achieve, but I don't have enough context so suggest alternatives.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants