Emscripten std::thread::sleep


#1

I’m having a quite specific problem with std::thread::sleep in wasm.

The problem is that instead of yielding to the render thread, it hangs the whole browser.

I don’t know if this is a bug in firefox (that I’m using), emscripten, rustc, or my code. Any help would be appreciated.

My expected behaviour is to yield for 1s then resume running (i.e. window.setTimeout in js)


#2

Is it even possible? setTimeout requires a separate closure, and sleep can be encountered anywhere inside a function. If a function has no loops and jumps, it’s more or less straightforward to split it at the location of the sleep call and turn the second part into a separate function that can be passed to setTimeout. There would still be a need to restore all local variables. But if you imagine a function with multiple loops, if blocks and multiple sleep calls, it quickly becomes very complex. It needs to be able to restore all variables and jump to any instruction after sleep.

There is a discussion about sleep being synchronous in this issue.

I think the right way is to use setTimeout call directly. I don’t have much experience with emscripten though, so there may be a better way.


#3

To answer my own question, there is an emscripten function emscripten_sleep_with_yield that takes a time to sleep in milliseconds.