From 3018eacc620e93859ed379e58197568ebe3a12c9 Mon Sep 17 00:00:00 2001
From: Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
Date: Sat, 22 Jul 2023 07:35:27 +0000
Subject: [PATCH v10] Have a quick exit for LWLockUpdateVar when there are no
 waiters

---
 src/backend/storage/lmgr/lwlock.c | 13 +++++++++++++
 1 file changed, 13 insertions(+)

diff --git a/src/backend/storage/lmgr/lwlock.c b/src/backend/storage/lmgr/lwlock.c
index ec7b55ffa8..86155cc977 100644
--- a/src/backend/storage/lmgr/lwlock.c
+++ b/src/backend/storage/lmgr/lwlock.c
@@ -1756,6 +1756,19 @@ LWLockUpdateVar(LWLock *lock, pg_atomic_uint64 *valptr, uint64 val)
 	 */
 	pg_atomic_exchange_u64(valptr, val);
 
+	/*
+	 * Quick exit when there are no waiters.
+	 *
+	 * The twice-in-a-row lock acquisition protocol used by LWLockWaitForVar is
+	 * helping us out have quick exit here when there are no waiters without
+	 * acquiring LWLock wait list lock. LWLockWaitForVar ensures that the
+	 * waiters are added to wait queue even if LWLockUpdateVar thinks that
+	 * there aren't any waiters actually. This avoids unnecessary LWLock wait
+	 * list lock acquisition and release when there are no waiters at all.
+	 */
+	if ((pg_atomic_read_u32(&lock->state) & LW_FLAG_HAS_WAITERS) == 0)
+		return;
+
 	proclist_init(&wakeup);
 
 	LWLockWaitListLock(lock);
-- 
2.34.1

