I am building a compiler targeting WebAssembly for a language that makes heavy use of first-class coroutines. WASM doesn't have native coroutine support (yet), so I have to emulate it. Given the native tools that WebAssembly does provide, what is the most suitable approach to implementing them?

These are primarily within-language coroutines, but calls out to platform functionality will occur within them occasionally. Coroutines are currently stackless but ubiquitous. I am primarily interested in browser-based execution, but ideally it would work on other WASM environments as well.

  • $\begingroup$ Is this in particular about Simultaneous Co-routines aka threads, or Asymmetric Co-routines like Lua? $\endgroup$
    – ATaco
    Commented May 28, 2023 at 22:39
  • $\begingroup$ @ATaco Asymmetric. $\endgroup$
    – Michael Homer
    Commented May 28, 2023 at 22:46
  • $\begingroup$ Cooperative stackless coroutines are State Machines (Automata) in disguise, aren't they? Thus you'll need to transform them into explicit SMs in a usual way (like Async in C# or Rust or pretty much everywhere), and add a shim to switch from one machine to another on top of that. At least that's how I understand your question... $\endgroup$ Commented May 29, 2023 at 7:40
  • $\begingroup$ @AlexChichigin State machines could form the basis of an answer. Any means of implementing these in WebAssembly is in scope. $\endgroup$
    – Michael Homer
    Commented May 29, 2023 at 8:49
  • $\begingroup$ @MichaelHomer pretty much the only way you can't implement a state machine in Wasm is via mutual tail-recursive functions. Not until tail calls proposal stabilizes. Every other approach from any other language should work. Modulo manual implementation of OOP and alike. A Wikipedia article has a number of examples. $\endgroup$ Commented May 30, 2023 at 15:00

1 Answer 1


For Symmetrically, Not Natively, However...

Web Assembly does not provide a native solution to multiple threads, meaning each solution will have to be platform specific.

You will need to import a function that handles messaging on the target platform for the purpose of spawning and communicating between threads, this can be handled in Javascript via Web-Workers.

Exact implementation will of course depend on the language details.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .