Fibers
Suspending the whole call stack or just one frame — PHP 8.1 Fiber against the concurrency-primitive spectrum of 10 languages.
C C23
#include <stdio.h>
/* C has no coroutine primitive in the standard library (ucontext exists on
POSIX but is deprecated on many platforms); the portable stand-in is a
hand-written state machine driven by explicit steps */
typedef struct {
int state;
int value;
} Fiber;
static const char *fiber_step(Fiber *f, int injected) {
switch (f->state) {
case 0:
f->value = injected + 1;
f->state = 1;
return "step 1";
case 1:
f->value += injected;
f->state = 2;
return "step 2";
default:
return "done";
}
}
int main(void) {
Fiber f = { .state = 0 };
printf("%s (%d)\n", fiber_step(&f, 0), f.value);
printf("%s (%d)\n", fiber_step(&f, 10), f.value);
printf("%s\n", fiber_step(&f, 0));
return 0;
}
step 1 (1) step 2 (11) done
C++ C++26
#include <cstdio>
#include <coroutine>
// a minimal generator over C++20 coroutines: co_yield suspends the frame
// and the caller drives resumption explicitly
struct Generator {
struct promise_type {
int current;
Generator get_return_object() {
return Generator{std::coroutine_handle<promise_type>::from_promise(*this)};
}
std::suspend_always initial_suspend() noexcept { return {}; }
std::suspend_always final_suspend() noexcept { return {}; }
std::suspend_always yield_value(int v) { current = v; return {}; }
void return_void() {}
void unhandled_exception() {}
};
std::coroutine_handle<promise_type> h;
explicit Generator(std::coroutine_handle<promise_type> hh) : h(hh) {}
Generator(const Generator &) = delete;
Generator &operator=(const Generator &) = delete;
Generator(Generator &&o) noexcept : h(o.h) { o.h = {}; }
Generator &operator=(Generator &&o) noexcept {
if (this != &o) { if (h) h.destroy(); h = o.h; o.h = {}; }
return *this;
}
~Generator() { if (h) h.destroy(); }
bool next() {
h.resume();
return !h.done();
}
int value() const { return h.promise().current; }
};
Generator counter() {
co_yield 1;
co_yield 2;
}
int main() {
Generator g = counter();
while (g.next()) std::printf("yield %d\n", g.value());
std::printf("done\n");
return 0;
}
yield 1 yield 2 done
C# v11.0.100
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
await CountAsync();
Console.WriteLine("done");
async Task CountAsync()
{
Console.WriteLine("before await");
await new SyncAwaiter(); // IsCompleted=true: the continuation runs inline
Console.WriteLine("after await");
}
// a never-yielding awaiter: the async state machine never actually yields
struct SyncAwaiter : INotifyCompletion
{
public SyncAwaiter GetAwaiter() => this;
public bool IsCompleted => true;
public void GetResult() { }
public void OnCompleted(Action continuation) { }
}
before await after await done
Go v1.27.4
package main
import "fmt"
// goroutines are preemptively scheduled; the channel forces the rendezvous
// points, so the interleaving below is deterministic
func worker(ch chan string) {
ch <- "from goroutine"
}
func main() {
ch := make(chan string)
go worker(ch)
fmt.Println(<-ch) // receive blocks until the goroutine sends
done := make(chan struct{})
go func() {
fmt.Println("second goroutine")
close(done)
}()
<-done
fmt.Println("main done")
}
from goroutine second goroutine main done
Java v27.0.1
public class Main {
public static void main(String[] args) throws Exception {
// virtual threads (Java 21+): cheap concurrency, mounted onto
// carrier OS threads by the JVM scheduler
Thread a = Thread.ofVirtual().unstarted(() -> System.out.println("vthread a"));
a.start();
a.join();
Thread b = Thread.ofVirtual().unstarted(() -> System.out.println("vthread b"));
b.start();
b.join();
System.out.println("main done");
}
}
vthread a vthread b main done
JavaScript v26.13.1
async function worker() {
console.log("A worker: before await");
const v = await Promise.resolve("value");
console.log("C worker: resumed with " + v);
}
const p = worker(); // runs synchronously up to the first await
console.log("B main: sync code runs while the coroutine waits");
p.then(() => console.log("D worker: settled"));
A worker: before await B main: sync code runs while the coroutine waits C worker: resumed with value D worker: settled
PHP v8.6.0
// start/suspend/resume: the fiber and main hand control back and forth
$fiber = new Fiber(function (): void {
echo "1 fiber: before suspend\n";
$v = Fiber::suspend("first");
echo "3 fiber: resumed with $v\n";
$w = Fiber::suspend("second");
echo "5 fiber: resumed with $w\n";
});
$v1 = $fiber->start();
echo "2 main: got $v1\n";
$v2 = $fiber->resume("ping");
echo "4 main: got $v2\n";
$fiber->resume("pong");
echo "6 main: terminated = ", var_export($fiber->isTerminated(), true), "\n";
1 fiber: before suspend 2 main: got first 3 fiber: resumed with ping 4 main: got second 5 fiber: resumed with pong 6 main: terminated = true
Python v3.15.2
import asyncio
async def worker():
print("2 worker: before await")
await asyncio.sleep(0) # yield control to the event loop
print("3 worker: resumed")
async def main():
task = asyncio.create_task(worker())
print("1 main: task scheduled, control stays here")
await task
print("4 main: task done")
asyncio.run(main())
1 main: task scheduled, control stays here 2 worker: before await 3 worker: resumed 4 main: task done
Rust v1.99.1
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
// Rust ships the Future model but no runtime; a minimal block_on can be
// hand-rolled with the standard library alone (real code uses tokio etc.)
fn noop_waker() -> Waker {
fn clone(_: *const ()) -> RawWaker {
RawWaker::new(std::ptr::null(), &VTABLE)
}
fn noop(_: *const ()) {}
static VTABLE: RawWakerVTable = RawWakerVTable::new(clone, noop, noop, noop);
// SAFETY: the vtable functions never dereference the null data pointer
unsafe { Waker::from_raw(RawWaker::new(std::ptr::null(), &VTABLE)) }
}
fn block_on<F: Future>(fut: F) -> F::Output {
let mut fut = Box::pin(fut);
let waker = noop_waker();
let mut cx = Context::from_waker(&waker);
loop {
match fut.as_mut().poll(&mut cx) {
Poll::Ready(v) => return v,
Poll::Pending => std::thread::yield_now(),
}
}
}
struct Done;
impl Future for Done {
type Output = &'static str;
fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
Poll::Ready("done")
}
}
fn main() {
println!("before await");
println!("{}", block_on(Done));
println!("after await");
}
before await done after await
TypeScript v26.13.1
// same stackless coroutines as JS; types only document the flow
async function worker(): Promise<string> {
console.log("A worker: before await");
const v = await Promise.resolve("value");
console.log("C worker: resumed with " + v);
return v;
}
const p = worker();
console.log("B main: sync code runs while the coroutine waits");
p.then(() => console.log("D worker: settled"));
A worker: before await B main: sync code runs while the coroutine waits C worker: resumed with value D worker: settled
Language differences
C: the standard library has no coroutine primitive (example): the portable stand-in is a hand-written state machine; POSIX ucontext can build stackful coroutines but is deprecated on many platforms and setjmp/longjmp tricks are brittle — modern C concurrency goes through the thread library.
C++: C++20 coroutines are a framework-level primitive (example): the language hands you co_yield/co_await plus the promise_type contract, and even a generator costs a few dozen lines; it is the stackless model — suspension points live only inside the coroutine frame.
C#: async/await (example): the compiler rewrites it into a state machine — a stackless coroutine; the example uses an IsCompleted=true awaiter to expose the await seam itself, while real yielding rides the Task scheduler.
Go: goroutines are preemptively scheduled (example): stackful, preempted by the runtime at any safe point (async preemption since 1.14), with channels as the rendezvous points; the cooperation/preemption boundary is the scheduler's business and invisible to user code.
Java: virtual threads, 21+ (example): a JVM-level stackful primitive where blocking calls are mounted and unmounted onto carrier threads; the closest cousin of PHP's Fiber — the whole call stack suspends and callers need no rewrite.
JavaScript: async/await and generators are both stackless (example): await suspends only the async function's own frame, and a deep call stack cannot pause mid-flight; the example shows the deterministic microtask interleaving.
PHP: 8.1+ Fibers (example): stackful coroutines — Fiber::suspend can suspend the entire stack at any depth, resume injects a value, throw delivers an exception inward; the start/suspend/resume handoff sequence is exactly the sample output; the essential contrast with generators: callers never see a Generator come back.
Python: asyncio coroutines (example): async def + await is stackless, and after create_task control returns to the main coroutine first (the sample sequence shows exactly that); generator yield is the other stackless branch of the family.
Rust: Future plus a hand-rolled executor (example): the language defines only the poll model, runtimes (tokio et al.) live in the ecosystem; stackless coroutines transformed into state machines by the compiler; the sample builds a minimal block_on from the standard library alone.
TypeScript: same stackless coroutines as JS (example): async/await suspends one frame; the type layer shapes Promise flows without changing semantics.