[libvirt PATCH v5 3/9] virthread: Introduce VIR_WITH_MUTEX_LOCK_GUARD

Tim Wiederhake posted 9 patches 4 years ago
[libvirt PATCH v5 3/9] virthread: Introduce VIR_WITH_MUTEX_LOCK_GUARD
Posted by Tim Wiederhake 4 years ago
Modeled after "WITH_QEMU_LOCK_GUARD" (see qemu's include/qemu/lockable.h).

See comment for typical usage.

Signed-off-by: Tim Wiederhake <twiederh@redhat.com>
---
 src/util/virthread.h | 21 +++++++++++++++++++++
 1 file changed, 21 insertions(+)

diff --git a/src/util/virthread.h b/src/util/virthread.h
index 6cdaf2820e..23abe0b6c9 100644
--- a/src/util/virthread.h
+++ b/src/util/virthread.h
@@ -209,3 +209,24 @@ int virThreadLocalSet(virThreadLocal *l, void*) G_GNUC_WARN_UNUSED_RESULT;
         return 0; \
     } \
     struct classname ## EatSemicolon
+
+#define VIR_WITH_MUTEX_LOCK_GUARD_(m, name) \
+    for (g_auto(virLockGuard) name = virLockGuardLock(m); name.mutex; \
+        name.mutex = (virLockGuardUnlock(&name), NULL))
+/**
+ * VIR_WITH_MUTEX_LOCK_GUARD:
+ *
+ * This macro defines a lock scope such that entering the scope takes the lock
+ * and leaving the scope releases the lock. Return statements are allowed
+ * within the scope and release the lock. Break and continue statements leave
+ * the scope early and release the lock.
+ *
+ *     virMutex *mutex = ...;
+ *
+ *     VIR_WITH_MUTEX_LOCK_GUARD(mutex) {
+ *         // `mutex` is locked, and released automatically on scope exit
+ *         ...
+ *     }
+ */
+#define VIR_WITH_MUTEX_LOCK_GUARD(m) \
+    VIR_WITH_MUTEX_LOCK_GUARD_(m, CONCAT(var, __COUNTER__))
-- 
2.31.1

Re: [libvirt PATCH v5 3/9] virthread: Introduce VIR_WITH_MUTEX_LOCK_GUARD
Posted by Daniel P. Berrangé 4 years ago
On Tue, Feb 01, 2022 at 02:20:11PM +0100, Tim Wiederhake wrote:
> Modeled after "WITH_QEMU_LOCK_GUARD" (see qemu's include/qemu/lockable.h).
> 
> See comment for typical usage.
> 
> Signed-off-by: Tim Wiederhake <twiederh@redhat.com>
> ---
>  src/util/virthread.h | 21 +++++++++++++++++++++
>  1 file changed, 21 insertions(+)

Reviewed-by: Daniel P. Berrangé <berrange@redhat.com>


Regards,
Daniel
-- 
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|