From b7d6798cfce2f62620c16eab48921a72630f5fa4 Mon Sep 17 00:00:00 2001 From: Wiebe Cazemier Date: Mon, 24 May 2021 20:10:58 +0200 Subject: [PATCH] Prevent deadlocks on lock you already own --- rwlockguard.cpp | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/rwlockguard.cpp b/rwlockguard.cpp index 4542e2f..15bae1c 100644 --- a/rwlockguard.cpp +++ b/rwlockguard.cpp @@ -36,10 +36,23 @@ void RWLockGuard::wrlock() throw std::runtime_error("wrlock failed."); } +/** + * @brief RWLockGuard::rdlock locks for reading, and considers it OK of the current thread already owns the lock for writing. + * + * The man page says: "The current thread already owns the read-write lock for writing." I hope that is literally the case. + */ void RWLockGuard::rdlock() { - if (pthread_rwlock_rdlock(rwlock) != 0) - throw std::runtime_error("rdlock failed."); + int rc = pthread_rwlock_rdlock(rwlock); + + if (rc == EDEADLK) + { + rwlock = NULL; + return; + } + + if (rc != 0) + throw std::runtime_error(strerror(rc)); } void RWLockGuard::unlock() -- libgit2 0.21.4