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. See comment for typical usage. Signed-off-by: Tim Wiederhake <twiederh@xxxxxxxxxx> --- src/util/virobject.h | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/util/virobject.h b/src/util/virobject.h index 0c9cbea726..a95985b69a 100644 --- a/src/util/virobject.h +++ b/src/util/virobject.h @@ -148,3 +148,23 @@ virObjectListFree(void *list); void virObjectListFreeCount(void *list, size_t count); + +/** + * VIR_WITH_OBJECT_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. + * + * virObjectLockable *lockable = ...; + * + * VIR_WITH_OBJECT_LOCK_GUARD(lockable) { + * // `lockable` is locked, and released automatically on scope exit + * ... + * } + */ +#define VIR_WITH_OBJECT_LOCK_GUARD(o) \ + for (g_autoptr(virLockGuard) CONCAT(var, __LINE__) = virObjectLockGuard(o); \ + CONCAT(var, __LINE__); \ + CONCAT(var, __LINE__) = (virLockGuardFree(CONCAT(var, __LINE__)), NULL)) -- 2.31.1