
On Fri, Jan 28, 2022 at 10:59:16AM +0100, Tim Wiederhake wrote:
Modeled after "WITH_QEMU_LOCK_GUARD" (see qemu's include/qemu/lockable.h). Uses "__LINE__" instead of "__COUNTER__", as the latter is a GNU extension.
GNU extensions are fine to use, as we explicitly only support GCC or CLang which is compatible with GCC, so I'd stick with __COUNTER__.
See comment for typical usage.
Signed-off-by: Tim Wiederhake <twiederh@redhat.com> --- src/util/virthread.h | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+)
diff --git a/src/util/virthread.h b/src/util/virthread.h index 6cdaf2820e..da17780908 100644 --- a/src/util/virthread.h +++ b/src/util/virthread.h @@ -209,3 +209,23 @@ int virThreadLocalSet(virThreadLocal *l, void*) G_GNUC_WARN_UNUSED_RESULT; return 0; \ } \ struct classname ## EatSemicolon + +/** + * 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) \ + for (g_auto(virLockGuard) CONCAT(var, __LINE__) = virLockGuardLock(m); \ + CONCAT(var, __LINE__).mutex; \ + CONCAT(var, __LINE__).mutex = (virLockGuardUnlock(& CONCAT(var, __LINE__)), NULL)) -- 2.31.1
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 :|