-
Notifications
You must be signed in to change notification settings - Fork 3.5k
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:
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.