Replace std::lock_guard and std::lock with std::scoped_lock (#1758)

std::scoped_lock was introduced in C++17 and is strictly better than
std::lock_guard as it supports locking any number of mutexes safely.
It's also easier to use than std::lock for locking multiple mutexes at
once.
This commit is contained in:
Tyler Veness
2019-07-08 22:58:39 -07:00
committed by Peter Johnson
parent 24d31df55a
commit 62be0392b6
79 changed files with 472 additions and 476 deletions

View File

@@ -29,7 +29,7 @@ detail::SafeThreadOwnerBase::~SafeThreadOwnerBase() {
}
void detail::SafeThreadOwnerBase::Start(std::shared_ptr<SafeThread> thr) {
std::lock_guard lock(m_mutex);
std::scoped_lock lock(m_mutex);
if (auto thr = m_thread.lock()) return;
m_stdThread = std::thread([=] { thr->Main(); });
thr->m_threadId = m_stdThread.get_id();
@@ -37,7 +37,7 @@ void detail::SafeThreadOwnerBase::Start(std::shared_ptr<SafeThread> thr) {
}
void detail::SafeThreadOwnerBase::Stop() {
std::lock_guard lock(m_mutex);
std::scoped_lock lock(m_mutex);
if (auto thr = m_thread.lock()) {
thr->m_active = false;
thr->m_cond.notify_all();
@@ -63,26 +63,24 @@ void detail::SafeThreadOwnerBase::Join() {
void detail::swap(SafeThreadOwnerBase& lhs, SafeThreadOwnerBase& rhs) noexcept {
using std::swap;
if (&lhs == &rhs) return;
std::lock(lhs.m_mutex, rhs.m_mutex);
std::lock_guard lock_lhs(lhs.m_mutex, std::adopt_lock);
std::lock_guard lock_rhs(rhs.m_mutex, std::adopt_lock);
std::scoped_lock lock(lhs.m_mutex, rhs.m_mutex);
std::swap(lhs.m_stdThread, rhs.m_stdThread);
std::swap(lhs.m_thread, rhs.m_thread);
}
detail::SafeThreadOwnerBase::operator bool() const {
std::lock_guard lock(m_mutex);
std::scoped_lock lock(m_mutex);
return !m_thread.expired();
}
std::thread::native_handle_type
detail::SafeThreadOwnerBase::GetNativeThreadHandle() {
std::lock_guard lock(m_mutex);
std::scoped_lock lock(m_mutex);
return m_stdThread.native_handle();
}
std::shared_ptr<SafeThread> detail::SafeThreadOwnerBase::GetThreadSharedPtr()
const {
std::lock_guard lock(m_mutex);
std::scoped_lock lock(m_mutex);
return m_thread.lock();
}