emscripten-core / emscripten-core/emscripten

std::mutex does nothing without -pthread

Open
#23,661 4 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

If the `-pthread` flag is not used when linking, `std::mutex` does nothing.

I imagine this seemed like a good idea at one stage, when the only way to get multithreaded behaviour was with `-pthread`. This also mirrors the (similarly surprising) behaviour of glibc when building without -pthreads: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58929

However, it's currently possible to have a multithreaded program with web workers (`-sWASM_WORKERS`) without using pthreads, and having a working `std::mutex` is still very desirable in that situation.

A simple test program to confirm whether mutex is working as expected or not:
```cpp
std::mutex test_mutex;
{
std::cout << "locking 1" << std::endl;
std::unique_lock lock1{test_mutex};
{
std::cout << "locking 2" << std::endl;
if(std::unique_lock lock{test_mutex, std::try_to_lock}; lock.owns_lock()){
std::cout << "lock 2 succeeded" << std::endl;
} else {
std::cout << "lock 2 failed" << std::endl;
}
std::cout << "anticipating deadlock after this point..." << std::endl;
std::unique_lock lock2{test_mutex};
// should not advance past this point due to deadlock
std::cout << "unlocking 2" << std::endl;
}
std::cout << "unlocking 1" << std::endl;
}
```

With `-pthread` enabled, this behaves as expected:
> locking 1
> locking 2
> lock 2 failed
> anticipating deadlock after this point...
> [program freezes]

Without `-pthread`:
> locking 1
> locking 2
> lock 2 succeeded
> anticipating deadlock after this point...
> unlocking 2
> unlocking 1

It's worth noting that `emscripten_lock_try_acquire` and associated functions work fine both without `-pthread`, only the `std::mutex` behaviour is surprising.

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.