4 ms·
"Fibers", "green threads", "stack switching", "cooperative multitasking" are essentially all the same thing, they all rely on being able to switch execution con
by flohofwoe 3y ago
"Fibers", "green threads", "stack switching", "cooperative multitasking" are essentially all the same thing, they all rely on being able to switch execution context by switching to a different stack within the same OS thread. As such they can be implemented either in (CPU/OS-specific) user code or in "OS APIs" (like the Windows Fiber functions).
Only downside of the technique is that it cannot be implemented in WASM (and maybe some other esoteric runtime environments), because WASM has separate data- and call-stacks and the call stack is not accessible from within the WASM virtual machine (while 'async-await' which relies on code transformation done by the compiler can be implemented in WASM just fine).
There is a 'stack-switching proposal' for WASM though, but I don't know what's the state of that:
https://github.com/WebAssembly/stack-switching https://github.com/WebAssembly/stack-switching
- gary_0 3y agoI've always been curious why WASM has the program flow restrictions it has. Most "ASM" just lets you set whatever register. There isn't much sandboxing value (WASM shouldn't be able to touch addresses outside the sandbox anyways). Was the reason ease of compilation/optimization for arbitrary architectures? Easier to run inside an interpreter? The default idea for WASM feels like it should have been more like RISC-V (but with enough wiggle-room to allow easy JITing to x86/ARM). Or are most of WASM's quirks just because it has ASM.js in its lineage?
- couchand 3y agoHaving a native stack switch for WASM would be nice but it's not necessary. Map all memory segments as shared into several instances of a single module -- each instance is a fiber. Implementation is left as an exercise for the reader.
- kevingadd 3y agoThis doesn't address the shadow stack at all. It doesn't work.
- couchand 3y agoEach instance has its own stack. Switching between them is cooperative on a single thread. What am I missing?
- kevingadd 3y agoWebAssembly stores stack data - parameters, return addresses, local variables - in a "shadow stack" that does not live in the native heap your application has access to. There's no way for you to switch it.
- couchand 3y agoEach instantiated module has its own complete function call stack. A call out of the module, to a bit of control code in JS, and then into a different instance of the same module, with the same memory mappings, would look (to the program itself) like a stack switch, no? I guess it raises the philosophical question of what is a stack switch, anyway? If you end up cooperatively running multiple "green threads" within a single "OS thread" does it matter that what you actually switched was the entire execution environment?