Skip to content

Single binary for multithreaded and singlethreaded code #1576

Open

Description

@eugeneko

This page 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, with all pthread-related flags
  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;
}
  1. 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

PS: I only tested PTHREAD_POOL_SIZE mode. I did not bother trying PROXY_TO_PTHREAD, my gut says it won't work as easily.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions