Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit a4b09af

Browse files
committed
Micro optimize LWLockAttemptLock() a bit.
LWLockAttemptLock pointlessly read the lock's state in every loop iteration, even though pg_atomic_compare_exchange_u32() returns the old value. Instead do that only once before the loop iteration. Additionally there's no need to have the expected_state variable, old_state mostly had the same value anyway. Noticed-By: Heikki Linnakangas Backpatch: 9.5, no reason to let the branches diverge at this point
1 parent 7039760 commit a4b09af

File tree

1 file changed

+12
-8
lines changed

1 file changed

+12
-8
lines changed

src/backend/storage/lmgr/lwlock.c

+12-8
Original file line numberDiff line numberDiff line change
@@ -582,29 +582,33 @@ LWLockInitialize(LWLock *lock, int tranche_id)
582582
static bool
583583
LWLockAttemptLock(LWLock *lock, LWLockMode mode)
584584
{
585+
uint32 old_state;
586+
585587
AssertArg(mode == LW_EXCLUSIVE || mode == LW_SHARED);
586588

589+
/*
590+
* Read once outside the loop, later iterations will get the newer value
591+
* via compare & exchange.
592+
*/
593+
old_state = pg_atomic_read_u32(&lock->state);
594+
587595
/* loop until we've determined whether we could acquire the lock or not */
588596
while (true)
589597
{
590-
uint32 old_state;
591-
uint32 expected_state;
592598
uint32 desired_state;
593599
bool lock_free;
594600

595-
old_state = pg_atomic_read_u32(&lock->state);
596-
expected_state = old_state;
597-
desired_state = expected_state;
601+
desired_state = old_state;
598602

599603
if (mode == LW_EXCLUSIVE)
600604
{
601-
lock_free = (expected_state & LW_LOCK_MASK) == 0;
605+
lock_free = (old_state & LW_LOCK_MASK) == 0;
602606
if (lock_free)
603607
desired_state += LW_VAL_EXCLUSIVE;
604608
}
605609
else
606610
{
607-
lock_free = (expected_state & LW_VAL_EXCLUSIVE) == 0;
611+
lock_free = (old_state & LW_VAL_EXCLUSIVE) == 0;
608612
if (lock_free)
609613
desired_state += LW_VAL_SHARED;
610614
}
@@ -620,7 +624,7 @@ LWLockAttemptLock(LWLock *lock, LWLockMode mode)
620624
* Retry if the value changed since we last looked at it.
621625
*/
622626
if (pg_atomic_compare_exchange_u32(&lock->state,
623-
&expected_state, desired_state))
627+
&old_state, desired_state))
624628
{
625629
if (lock_free)
626630
{

0 commit comments

Comments
 (0)