mackron / miniaudio

Audio playback and capture library written in C, in a single source file.
https://miniaud.io
Other
3.76k stars 324 forks source link

emscripten threading #855

Open digitalsignalperson opened 1 month ago

digitalsignalperson commented 1 month ago

Hi, I'm curious what the challenges to move forward with emscripten threading.

As of today:

Emscripten has support for multithreading using SharedArrayBuffer in browsers. That API allows sharing memory between the main thread and web workers as well as atomic operations for synchronization, which enables Emscripten to implement support for the Pthreads (POSIX threads) API. This support is considered stable in Emscripten.

from https://emscripten.org/docs/porting/pthreads.html

mackron commented 1 month ago

That first note at the top of that article isn't something I find appealing. I'm not much of a web person and I don't know anything about COOP or COEP so not entirely sure what the implications are on that front, but miniaudio needs to "just work", so certainly enabling pthreads wholesale without an option to disable it sounds bad considering that note.

When using pthreads with Emscripten, is it using actual real threads, or is it just emulating it? If it's just emulating it, what are the tangible real-world benefits you'd get out of it? Looking at that article they make it sound like it's real threads?

digitalsignalperson commented 1 month ago

Thanks for those questions. Looking into it a bit, this is what I understand:

So for miniaudio, I think if the emscripten builds used pthreads, everything "just works". And if anyone wants to do the extra work to compile with -pthread and serve their site with COOP/COEP headers, then it doesn't actually change any code on the miniaudio side.

This blog was helpful https://unlimited3d.wordpress.com/2021/12/21/webassembly-and-multi-threading/ including the sections on "Cross-origin isolation headers" / "Isolating multi-threaded WebAssembly – what for?" to motivate why COOP/COEP are involved.

mackron commented 1 month ago

If I'm reading the Emscripten documentation correctly, it looks like __EMSCRIPTEN_PTHREADS__ will be defined if -pthread is being used. That, combined with it using actual real threads, probably makes it a reasonable thing to support in miniaudio. I'm assuming if __EMSCRIPTEN_PTHREADS__ is enabled, we just use pthreads like any other platform, and otherwise just leave it like it is now. Don't expect there to be too much additional code maintenance. I'll leave this ticket open and investigate when I get a chance. No time frame. Thanks for making me aware of this.