Merge pull request #66745 from ClickHouse/dbg_shared_mutex

Save writer thread id in shared mutex for debugging
This commit is contained in:
Alexander Gololobov 2024-07-30 08:39:35 +00:00 committed by GitHub
commit 41127d818d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 15 additions and 1 deletions

View File

@ -1,4 +1,5 @@
#include <Common/SharedMutex.h>
#include <base/getThreadId.h>
#ifdef OS_LINUX /// Because of futex
@ -12,6 +13,7 @@ namespace DB
SharedMutex::SharedMutex()
: state(0)
, waiters(0)
, writer_thread_id(0)
{}
void SharedMutex::lock()
@ -29,6 +31,10 @@ void SharedMutex::lock()
break;
}
/// The first step of acquiring the exclusive ownership is finished.
/// Now we just wait until all readers release the shared ownership.
writer_thread_id.store(getThreadId());
value |= writers;
while (value & readers)
futexWaitLowerFetch(state, value);
@ -37,11 +43,15 @@ void SharedMutex::lock()
bool SharedMutex::try_lock()
{
UInt64 value = 0;
return state.compare_exchange_strong(value, writers);
bool success = state.compare_exchange_strong(value, writers);
if (success)
writer_thread_id.store(getThreadId());
return success;
}
void SharedMutex::unlock()
{
writer_thread_id.store(0);
state.store(0);
if (waiters)
futexWakeUpperAll(state);

View File

@ -19,6 +19,8 @@ public:
~SharedMutex() = default;
SharedMutex(const SharedMutex &) = delete;
SharedMutex & operator=(const SharedMutex &) = delete;
SharedMutex(SharedMutex &&) = delete;
SharedMutex & operator=(SharedMutex &&) = delete;
// Exclusive ownership
void lock() TSA_ACQUIRE();
@ -36,6 +38,8 @@ private:
alignas(64) std::atomic<UInt64> state;
std::atomic<UInt32> waiters;
/// Is set while the lock is held (or is in the process of being acquired) in exclusive mode only to facilitate debugging
std::atomic<UInt64> writer_thread_id;
};
}