ClickHouse/src/Common/SharedMutex.cpp

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

100 lines
2.0 KiB
C++
Raw Normal View History

2023-01-09 14:58:44 +00:00
#include <Common/SharedMutex.h>
2024-07-19 11:26:35 +00:00
#include <base/getThreadId.h>
2023-01-09 14:58:44 +00:00
#ifdef OS_LINUX /// Because of futex
#include <bit>
#include <Common/futex.h>
namespace DB
{
2023-01-10 16:35:46 +00:00
SharedMutex::SharedMutex()
: state(0)
, waiters(0)
2024-07-19 11:26:35 +00:00
, writer_thread_id(0)
2023-01-10 16:35:46 +00:00
{}
2023-01-09 14:58:44 +00:00
void SharedMutex::lock()
{
UInt64 value = state.load();
while (true)
{
if (value & writers)
{
waiters++;
futexWaitUpperFetch(state, value);
waiters--;
}
else if (state.compare_exchange_strong(value, value | writers))
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());
2023-01-09 14:58:44 +00:00
value |= writers;
while (value & readers)
futexWaitLowerFetch(state, value);
}
bool SharedMutex::try_lock()
{
UInt64 value = 0;
2024-07-19 11:26:35 +00:00
bool success = state.compare_exchange_strong(value, writers);
if (success)
writer_thread_id.store(getThreadId());
return success;
2023-01-09 14:58:44 +00:00
}
void SharedMutex::unlock()
{
2024-07-19 11:26:35 +00:00
writer_thread_id.store(0);
2023-01-09 14:58:44 +00:00
state.store(0);
if (waiters)
futexWakeUpperAll(state);
}
void SharedMutex::lock_shared()
{
UInt64 value = state.load();
while (true)
{
if (value & writers)
{
waiters++;
futexWaitUpperFetch(state, value);
waiters--;
}
else if (state.compare_exchange_strong(value, value + 1))
break;
}
}
bool SharedMutex::try_lock_shared()
{
UInt64 value = state.load();
while (true)
{
if (value & writers)
return false;
if (state.compare_exchange_strong(value, value + 1))
break;
// Concurrent try_lock_shared() should not fail, so we have to retry CAS, but avoid blocking wait
}
return true;
2023-01-09 14:58:44 +00:00
}
void SharedMutex::unlock_shared()
{
UInt64 value = state.fetch_sub(1) - 1;
if (value == writers)
futexWakeLowerOne(state); // Wake writer
}
}
#endif