8
votes

I'm trying to use thread with Emscripten and I don't understand how it work. I've read some text about web workers and I'm not sure to understand.

When I take a look in "tests" folder, I can see pthread stuff.

I'm using "std::thread" and got the following error:

unresolved symbol: pthread_create

Did I have to use web workers instead of default thread?

Thanks!

2
It now requires headers on the server for pthreads to work on Emscripten dzone.com/articles/webassembly-threads-in-firefox developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… - eri0o

2 Answers

10
votes

The support for pthread is being added and can already be used with a bit of setup. Since std::thread is using pthread under the hood, you can use it as well. See this discussion for more information.

What I had to do:

  • Use a newer emscripten (I'm testing with 1.34.1)
  • Install Firefox Nightly
  • Enable the flag USE_PTHREADS
  • Be mindful that this is experimental and some things are finicky

I was having trouble writing up a pthread example that actually ran, but here's code using std::thread that demonstrates the basic functionality which worked for me:

// main.cpp

#include <thread>
#include <iostream>

void func()
{
    std::cout << "I'm a thread!\n";
}

int main()
{
    std::thread test1(func);
    std::thread test2(func);
    std::thread test3(func);

    // join seems to lock up the browser
    //test1.join();
    //test2.join();
    //test3.join();
}

I have been able to use the threading in a larger project (to large for a post here!), so they are viable. They are not all that fast, I'm afraid, though that may improve with time.

To build it:

emcc main.cpp -o main.html -s USE_PTHREADS=1 --std=c++11

Output in Firefox Nightly 42.0a1 (2015-07-16):

Preallocating 1 workers for a pthread spawn pool.
Preallocating 1 workers for a pthread spawn pool.
Preallocating 1 workers for a pthread spawn pool.
I'm a thread!
I'm a thread!
I'm a thread!

2
votes

Unfortunately, multi-threaded code cannot be compiled with Emscripten. Web workers allow simultaneous computation, but they can't maintain shared state and thus cannot substitute for threads.

See: http://kripken.github.io/emscripten-site/docs/porting/guidelines/portability_guidelines.html

Edit: As others have pointer out, Emscripten is moving forward since my original answer, and now has experimental support for pthreads (and likely soon for C++ built-in threads) https://groups.google.com/forum/#!topic/emscripten-discuss/gQQRjajQ6iY