Bird
0
0

You want to ensure two different sessions do not run a critical section simultaneously using advisory locks. Which approach is best?

hard📝 Application Q15 of 15
PostgreSQL - Transactions and Concurrency
You want to ensure two different sessions do not run a critical section simultaneously using advisory locks. Which approach is best?
-- Session 1 and 2 run this code:
SELECT pg_try_advisory_lock(42);
-- If true, run critical section, then
SELECT pg_advisory_unlock(42);
AUse pg_advisory_unlock before acquiring lock to clear old locks
BUse pg_try_advisory_lock to attempt lock and skip if busy
CUse pg_advisory_lock to wait until lock is available before running
DUse random keys each time to avoid conflicts
Step-by-Step Solution
Solution:
  1. Step 1: Understand locking strategies

    pg_try_advisory_lock returns immediately and may skip critical section if lock busy; pg_advisory_lock waits until lock is free.
  2. Step 2: Choose best approach for critical section

    To ensure only one session runs critical section at a time, waiting for the lock is safer than skipping it.
  3. Step 3: Evaluate other options

    Unlocking before acquiring is unsafe and random keys defeat locking purpose.
  4. Final Answer:

    Use pg_advisory_lock to wait until lock is available before running -> Option C
  5. Quick Check:

    Waiting lock ensures exclusive access [OK]
Quick Trick: Use pg_advisory_lock to wait for exclusive access [OK]
Common Mistakes:
  • Using try lock and skipping critical section silently
  • Unlocking before locking without owning lock
  • Using random keys causing no real locking

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes