Based on this question, I extended std::mutex
so that I can check if the mutex is already locked by the current thread:
class mutex : public std::mutex
{
public:
void lock()
{
std::mutex::lock();
lock_holder_ = std::this_thread::get_id();
}
void unlock()
{
lock_holder_ = std::thread::id();
std::mutex::unlock();
}
[[nodiscard]] bool locked_by_caller() const
{
return lock_holder_ == std::this_thread::get_id();
}
private:
std::atomic<std::thread::id> lock_holder_;
};
On Linux with GCC 9.x (via WSL on Windows 10, using Ubuntu 20.04 LTS), there is a segmentation fault thrown in the locked_by_caller()
function. When using Valgrind I get the following output:
==2120== Memcheck, a memory error detector
==2120== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==2120== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==2120== Command: ./WSL-GCC-Debug/eventbus/eventbus.tests
==2120==
==2120== error calling PR_SET_PTRACER, vgdb might block
Running main() from /mnt/d/repositories/eventbus/eventbus-src/out/build/WSL-GCC-Debug/_deps/googletest-src/googletest/src/gtest_main.cc
[==========] Running 4 tests from 2 test cases.
[----------] Global test environment set-up.
[----------] 3 tests from EventBusTestFixture
[ RUN ] EventBusTestFixture.LambdaRegistrationAndDeregistration
Lambda 3 take by copy.
Lambda 1
Lambda 3 take by copy.
Lambda 1
Lambda 3 take by copy.
Lambda 3 take by copy.
[ OK ] EventBusTestFixture.LambdaRegistrationAndDeregistration (83 ms)
[ RUN ] EventBusTestFixture.RegisterWhileDispatching
Loop 0 Handler count: 2
==2120== Invalid read of size 8
==2120== at 0x11C036: std::atomic<std::thread::id>::load(std::memory_order) const (atomic:254)
==2120== by 0x11AE5A: std::atomic<std::thread::id>::operator std::thread::id() const (atomic:207)
==2120== by 0x11A22E: dp::event_bus::mutex::locked_by_caller() const (event_bus.hpp:153)
And gdb
outputs the following:
Program received signal SIGSEGV, Segmentation fault.
std::atomic<std::thread::id>::load (this=0x2a, __m=std::memory_order_seq_cst) at /usr/include/c++/9/atomic:254
254 __atomic_load(std::__addressof(_M_i), __ptr, int(__m));
Segmentation fault
I noticed the invalid read of size 8
and after doing research I found that this was a bug (also on Stackoverflow) in an older version of GCC but was fixed in 5.x. Is this still an alignment problem because I'm using std::thread::id
in an std::atomic
? Are there any work around to this issue?
Full code (for context) is on my Github.