Single binary for multithreaded and singlethreaded code
threadsdocumentation
[This page](https://emscripten.org/docs/porting/pthreads.html) says
> It is not possible to build one binary that would be able to leverage multithreading when available and fall back to single threaded when not. The best you can do is two separate builds, one with and one without threads, and pick between them at runtime.
But it works fine for me? Why not?
I understand that I am testing single specific case, and it may be much more complicated in general.
I would like to know if what am I doing is a fluke, or it is general solution to the problem.
What I am doing:
1. Write code as if it is multithreaded
2. Add realtime c++ check whether to use threads:
```
bool hasWorkers() {
using namespace emscripten;
val PThread = val::global("PThread");
if (PThread.isUndefined()) {
return false;
}
int unused = PThread["unusedWorkers"]["length"].as<int>();
int running = PThread["runningWorkers"]["length"].as<int>();
return unused + running > 0;
}
```
3. Patch `initMainThread()` in main JS
```
var pthreadPoolSize = self.crossOriginIsolated ? 7 : 0;
```
And this works perfectly without any additional hacks or patches on current Chrome, for my app. I have a few warnings due to SharedArrayBuffers being referenced in code, but it does not explode until I try to create workers.
I have single page that (1) utilized threads fully when run with crossOriginIsolated and (2) runs without errors but slowly without crossOriginIsolated
0 条评论