revoltphp / revoltphp.github.io

MIT License
10 stars 1 forks source link

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

Open Kingdutch opened 8 months ago

Kingdutch commented 8 months ago

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 https://github.com/revoltphp/event-loop/issues/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 commented 8 months ago

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.