diff --git a/src/backend/storage/ipc/shm_mq.c b/src/backend/storage/ipc/shm_mq.c index 540f604c311..9e726eb628e 100644 --- a/src/backend/storage/ipc/shm_mq.c +++ b/src/backend/storage/ipc/shm_mq.c @@ -763,11 +763,11 @@ shm_mq_send_bytes(shm_mq_handle *mqh, Size nbytes, void *data, bool nowait, */ WaitLatch(&MyProc->procLatch, WL_LATCH_SET, 0); - /* An interrupt may have occurred while we were waiting. */ - CHECK_FOR_INTERRUPTS(); - /* Reset the latch so we don't spin. */ ResetLatch(&MyProc->procLatch); + + /* An interrupt may have occurred while we were waiting. */ + CHECK_FOR_INTERRUPTS(); } else { @@ -860,11 +860,11 @@ shm_mq_receive_bytes(shm_mq *mq, Size bytes_needed, bool nowait, */ WaitLatch(&MyProc->procLatch, WL_LATCH_SET, 0); - /* An interrupt may have occurred while we were waiting. */ - CHECK_FOR_INTERRUPTS(); - /* Reset the latch so we don't spin. */ ResetLatch(&MyProc->procLatch); + + /* An interrupt may have occurred while we were waiting. */ + CHECK_FOR_INTERRUPTS(); } } @@ -966,11 +966,11 @@ shm_mq_wait_internal(volatile shm_mq *mq, PGPROC *volatile * ptr, /* Wait to be signalled. */ WaitLatch(&MyProc->procLatch, WL_LATCH_SET, 0); - /* An interrupt may have occurred while we were waiting. */ - CHECK_FOR_INTERRUPTS(); - /* Reset the latch so we don't spin. */ ResetLatch(&MyProc->procLatch); + + /* An interrupt may have occurred while we were waiting. */ + CHECK_FOR_INTERRUPTS(); } } PG_CATCH(); diff --git a/src/include/storage/latch.h b/src/include/storage/latch.h index ab722e75662..fbd9e574566 100644 --- a/src/include/storage/latch.h +++ b/src/include/storage/latch.h @@ -52,6 +52,22 @@ * do. Otherwise, if someone sets the latch between the check and the * ResetLatch call, you will miss it and Wait will incorrectly block. * + * Another valid coding pattern looks like: + * + * for (;;) + * { + * if (work to do) + * Do Stuff(); // in particular, exit loop if some condition satisfied + * WaitLatch(); + * ResetLatch(); + * } + * + * This is useful to reduce latch traffic if it's expected that the loop's + * termination condition will often be satisfied in the first iteration; + * the cost is an extra loop iteration before blocking when it is not. + * What must be avoided is placing any checks for asynchronous events after + * WaitLatch and before ResetLatch, as that creates a race condition. + * * To wake up the waiter, you must first set a global flag or something * else that the wait loop tests in the "if (work to do)" part, and call * SetLatch *after* that. SetLatch is designed to return quickly if the