emscripten-core / emscripten-core/emscripten

Universal threading API

Open
#20,509 9 comments 0 reactions 0 assignees View on GitHub
Dominant language
C++
Stars
27.6k
Forks
3.6k
Avg merge
1d 1h
Merged PRs (30d)
105

Description

The emscripten provides two different and incompatible threading APIs. https://emscripten.org/docs/api_reference/wasm_workers.html

I experienced, that c++11 std::thread seems be compatible with PThreads, so I can use std::thread instead of pthread with compiling by this command:
`emcc thrtest.cpp -o thrtest.js -s "EXPORTED_RUNTIME_METHODS=['ccall']" -pthread -sPTHREAD_POOL_SIZE=5`

The second API is provided by compiling with this command:
`emcc thrtest.cpp -o thrtest.js -s "EXPORTED_RUNTIME_METHODS=['ccall']" -sWASM_WORKERS`

I wrote simple test code with thread and mutex:
```
#include
#include
#include
#include
#include

std::thread * Thr;

std::mutex MTX;
std::mutex MTX0;
std::string Str;

int Ptrx = 1;

bool UseMTX = true;

void ThrTestProc()
{
if (UseMTX) MTX0.lock();
for (int I = 0; I < 26; I++)
{
for (int I0 = 0; I0 < 1000; I0++)
{
Ptrx = Ptrx * 3;
Ptrx = Ptrx / 2;
}
MTX.lock();
std::string SX = "X";
SX[0] = ((char)(I + 65));
Str = Str + SX;
MTX.unlock();
}
if (UseMTX) MTX0.unlock();
}

void ThrTest()
{
printf("Thread test start\n");
for (int I = 0; I < 10; I++)
{
Str = "";
std::thread * Thr1 = new std::thread(ThrTestProc);
std::thread * Thr2 = new std::thread(ThrTestProc);
std::thread * Thr3 = new std::thread(ThrTestProc);
std::thread * Thr4 = new std::thread(ThrTestProc);
Thr1->join();
Thr2->join();
Thr3->join();
Thr4->join();
delete Thr1;
delete Thr2;
delete Thr3;
delete Thr4;
printf("%s\n", Str.c_str());
}
printf("Thread test stop\n");
}

EMSCRIPTEN_KEEPALIVE
void ThrTest1()
{
UseMTX = true;
ThrTest();
}

EMSCRIPTEN_KEEPALIVE
void ThrTest0()
{
UseMTX = false;
ThrTest();
}

int main()
{
printf("Thread test\n");

#ifdef __EMSCRIPTEN_PTHREADS__
printf("Posix thread\n");
#endif

#ifdef __EMSCRIPTEN_WASM_WORKERS__
printf("Wasm worker\n");
#endif

return 0;
}
```

If I compile as PThread, this code works very well, but if I compile as WASM worker, the thread does not run.

It is possible to enforce std::thread to use the WASM Worker API?

What is the `std::thread.join()` equivalent in WASM Worker API?

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.