Skip to content

Commit 3cac0ec

Browse files
committed
Reorder steps in ConditionVariablePrepareToSleep for more safety.
In the admittedly-very-unlikely case that AddWaitEventToSet fails, ConditionVariablePrepareToSleep would error out after already having set cv_sleep_target, which is probably bad, and after having already set cv_wait_event_set, which is very bad. Transaction abort might or might not clean up cv_sleep_target properly; but there is nothing that would be aware that the WaitEventSet wasn't fully constructed, so that all future condition variable sleeps would be broken. We can easily guard against these hazards with slight restructuring. Back-patch to v10 where condition_variable.c was introduced. Discussion: https://postgr.es/m/CAEepm=0NWKehYw7NDoUSf8juuKOPRnCyY3vuaSvhrEWsOTAa3w@mail.gmail.com
1 parent aced5a9 commit 3cac0ec

File tree

1 file changed

+15
-8
lines changed

1 file changed

+15
-8
lines changed

src/backend/storage/lmgr/condition_variable.c

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,21 @@ ConditionVariablePrepareToSleep(ConditionVariable *cv)
5454
{
5555
int pgprocno = MyProc->pgprocno;
5656

57+
/*
58+
* If first time through in this process, create a WaitEventSet, which
59+
* we'll reuse for all condition variable sleeps.
60+
*/
61+
if (cv_wait_event_set == NULL)
62+
{
63+
WaitEventSet *new_event_set;
64+
65+
new_event_set = CreateWaitEventSet(TopMemoryContext, 1);
66+
AddWaitEventToSet(new_event_set, WL_LATCH_SET, PGINVALID_SOCKET,
67+
MyLatch, NULL);
68+
/* Don't set cv_wait_event_set until we have a correct WES. */
69+
cv_wait_event_set = new_event_set;
70+
}
71+
5772
/*
5873
* It's not legal to prepare a sleep until the previous sleep has been
5974
* completed or canceled.
@@ -63,14 +78,6 @@ ConditionVariablePrepareToSleep(ConditionVariable *cv)
6378
/* Record the condition variable on which we will sleep. */
6479
cv_sleep_target = cv;
6580

66-
/* Create a reusable WaitEventSet. */
67-
if (cv_wait_event_set == NULL)
68-
{
69-
cv_wait_event_set = CreateWaitEventSet(TopMemoryContext, 1);
70-
AddWaitEventToSet(cv_wait_event_set, WL_LATCH_SET, PGINVALID_SOCKET,
71-
MyLatch, NULL);
72-
}
73-
7481
/*
7582
* Reset my latch before adding myself to the queue and before entering
7683
* the caller's predicate loop.

0 commit comments

Comments
 (0)