emscripten-core / emscripten-core/emscripten

exit() doesn't terminate workers

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

Description

Even after calling `exit()` in a multi-threaded program, the workers from the pool aren't terminated.

Demo source code:
```
#include

#include

void do_foo_in_thread() {
std::thread([]() {}).detach();
}

EMSCRIPTEN_BINDINGS(my_module) {
emscripten::function("do_foo_in_thread", &do_foo_in_thread);
}
```

page.html:
```


async function sleep(timeoutMillis) {
return new Promise(resolve => {
setTimeout(resolve, timeoutMillis);
});
}

var Module = {
onRuntimeInitialized: async function() {
function log_threads() {
console.log(`unusedWorkers=${Module.PThread.unusedWorkers.length},` +
`runningWorkers=${Module.PThread.runningWorkers.length}`);
}

log_threads();
console.log('triggering thread...');
Module.do_foo_in_thread();
log_threads();
console.log('sleeping...');
await sleep(1000);
log_threads();
console.log('calling exit...');
try {
Module._exit(0);
} catch (e) {
console.log(`error: ${e}`);
}
log_threads();
}
};

```

Result of the execution (note the last line):
```
unusedWorkers=0,runningWorkers=0
triggering thread...
unusedWorkers=0,runningWorkers=1
sleeping...
unusedWorkers=1,runningWorkers=0
calling exit...
error: NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'http://localhost:6931/stdio.html'.
unusedWorkers=1,runningWorkers=0
```

Note that when I replace the `Module._exit(0)` call with `Module.PThread.terminateAllThreads()`, the log indicates the behavior becomes the intended one (`unusedWorkers=0,runningWorkers=0`). However, it's unclear whether `PThread.terminateAllThreads()` can be used or should it be treated as Emscripten's internal implementation detail.

**Version of emscripten/emsdk:**
3.1.45

**Failing command line in full:**
```
emcc -lembind -g -O0 -pthread --emrun -sEXPORTED_FUNCTIONS=_exit embind.cc -o page.js && emrun page.html
```

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.