From 148cc03060b6b7e7e83289731fdf322ac74b2790 Mon Sep 17 00:00:00 2001 From: Zygo Blaxell Date: Sat, 19 Nov 2022 18:23:33 -0500 Subject: [PATCH] bytevector: do not deadlock in self-assignment Not that this is a particularly useful use case, but it will lock up, and it should not. Signed-off-by: Zygo Blaxell --- lib/bytevector.cc | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/lib/bytevector.cc b/lib/bytevector.cc index 1acbed3..5cf5069 100644 --- a/lib/bytevector.cc +++ b/lib/bytevector.cc @@ -60,11 +60,15 @@ namespace crucible { ByteVector& ByteVector::operator=(const ByteVector &that) { - unique_lock lock_this(m_mutex, defer_lock); - unique_lock lock_that(that.m_mutex, defer_lock); - lock(lock_this, lock_that); - m_ptr = that.m_ptr; - m_size = that.m_size; + // If &that == this, there's no need to do anything, but + // especially don't try to lock the same mutex twice. + if (&m_mutex != &that.m_mutex) { + unique_lock lock_this(m_mutex, defer_lock); + unique_lock lock_that(that.m_mutex, defer_lock); + lock(lock_this, lock_that); + m_ptr = that.m_ptr; + m_size = that.m_size; + } return *this; }