Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread using emscripten

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!

like image 486
user30088 Avatar asked Dec 14 '14 20:12

user30088


People also ask

Can WebAssembly do multithreading?

WebAssembly threads is not a separate feature, but a combination of several components that allows WebAssembly apps to use traditional multithreading paradigms on the web.

Does Rust use Emscripten?

It is possible to use Emscripten to compile Rust programs using C APIs to small WebAssembly binaries. They can be just as small as corresponding C programs, in fact, and those can be quite compact.

What is Pthread in Linux?

POSIX Threads, commonly known as pthreads, is an execution model that exists independently from a language, as well as a parallel execution model. It allows a program to control multiple different flows of work that overlap in time.


1 Answers

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!

like image 78
Joshua Brookover Avatar answered Oct 02 '22 12:10

Joshua Brookover