PostgreSQL Source Code  git master
condition_variable.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * condition_variable.c
4  * Implementation of condition variables. Condition variables provide
5  * a way for one process to wait until a specific condition occurs,
6  * without needing to know the specific identity of the process for
7  * which they are waiting. Waits for condition variables can be
8  * interrupted, unlike LWLock waits. Condition variables are safe
9  * to use within dynamic shared memory segments.
10  *
11  * Portions Copyright (c) 1996-2018, PostgreSQL Global Development Group
12  * Portions Copyright (c) 1994, Regents of the University of California
13  *
14  * src/backend/storage/lmgr/condition_variable.c
15  *
16  *-------------------------------------------------------------------------
17  */
18 
19 #include "postgres.h"
20 
21 #include "miscadmin.h"
23 #include "storage/ipc.h"
24 #include "storage/proc.h"
25 #include "storage/proclist.h"
26 #include "storage/spin.h"
27 #include "utils/memutils.h"
28 
29 /* Initially, we are not prepared to sleep on any condition variable. */
31 
32 /* Reusable WaitEventSet. */
34 
35 /*
36  * Initialize a condition variable.
37  */
38 void
40 {
41  SpinLockInit(&cv->mutex);
42  proclist_init(&cv->wakeup);
43 }
44 
45 /*
46  * Prepare to wait on a given condition variable.
47  *
48  * This can optionally be called before entering a test/sleep loop.
49  * Doing so is more efficient if we'll need to sleep at least once.
50  * However, if the first test of the exit condition is likely to succeed,
51  * it's more efficient to omit the ConditionVariablePrepareToSleep call.
52  * See comments in ConditionVariableSleep for more detail.
53  *
54  * Caution: "before entering the loop" means you *must* test the exit
55  * condition between calling ConditionVariablePrepareToSleep and calling
56  * ConditionVariableSleep. If that is inconvenient, omit calling
57  * ConditionVariablePrepareToSleep.
58  */
59 void
61 {
62  int pgprocno = MyProc->pgprocno;
63 
64  /*
65  * If first time through in this process, create a WaitEventSet, which
66  * we'll reuse for all condition variable sleeps.
67  */
68  if (cv_wait_event_set == NULL)
69  {
70  WaitEventSet *new_event_set;
71 
72  new_event_set = CreateWaitEventSet(TopMemoryContext, 2);
74  MyLatch, NULL);
76  NULL, NULL);
77  /* Don't set cv_wait_event_set until we have a correct WES. */
78  cv_wait_event_set = new_event_set;
79  }
80 
81  /*
82  * If some other sleep is already prepared, cancel it; this is necessary
83  * because we have just one static variable tracking the prepared sleep,
84  * and also only one cvWaitLink in our PGPROC. It's okay to do this
85  * because whenever control does return to the other test-and-sleep loop,
86  * its ConditionVariableSleep call will just re-establish that sleep as
87  * the prepared one.
88  */
89  if (cv_sleep_target != NULL)
91 
92  /* Record the condition variable on which we will sleep. */
93  cv_sleep_target = cv;
94 
95  /*
96  * Reset my latch before adding myself to the queue, to ensure that we
97  * don't miss a wakeup that occurs immediately.
98  */
100 
101  /* Add myself to the wait queue. */
102  SpinLockAcquire(&cv->mutex);
103  proclist_push_tail(&cv->wakeup, pgprocno, cvWaitLink);
104  SpinLockRelease(&cv->mutex);
105 }
106 
107 /*
108  * Wait for the given condition variable to be signaled.
109  *
110  * This should be called in a predicate loop that tests for a specific exit
111  * condition and otherwise sleeps, like so:
112  *
113  * ConditionVariablePrepareToSleep(cv); // optional
114  * while (condition for which we are waiting is not true)
115  * ConditionVariableSleep(cv, wait_event_info);
116  * ConditionVariableCancelSleep();
117  *
118  * wait_event_info should be a value from one of the WaitEventXXX enums
119  * defined in pgstat.h. This controls the contents of pg_stat_activity's
120  * wait_event_type and wait_event columns while waiting.
121  */
122 void
124 {
125  WaitEvent event;
126  bool done = false;
127 
128  /*
129  * If the caller didn't prepare to sleep explicitly, then do so now and
130  * return immediately. The caller's predicate loop should immediately
131  * call again if its exit condition is not yet met. This will result in
132  * the exit condition being tested twice before we first sleep. The extra
133  * test can be prevented by calling ConditionVariablePrepareToSleep(cv)
134  * first. Whether it's worth doing that depends on whether you expect the
135  * exit condition to be met initially, in which case skipping the prepare
136  * is recommended because it avoids manipulations of the wait list, or not
137  * met initially, in which case preparing first is better because it
138  * avoids one extra test of the exit condition.
139  *
140  * If we are currently prepared to sleep on some other CV, we just cancel
141  * that and prepare this one; see ConditionVariablePrepareToSleep.
142  */
143  if (cv_sleep_target != cv)
144  {
146  return;
147  }
148 
149  do
150  {
152 
153  /*
154  * Wait for latch to be set. (If we're awakened for some other
155  * reason, the code below will cope anyway.)
156  */
157  WaitEventSetWait(cv_wait_event_set, -1, &event, 1, wait_event_info);
158 
159  if (event.events & WL_POSTMASTER_DEATH)
160  {
161  /*
162  * Emergency bailout if postmaster has died. This is to avoid the
163  * necessity for manual cleanup of all postmaster children.
164  */
165  exit(1);
166  }
167 
168  /* Reset latch before examining the state of the wait list. */
170 
171  /*
172  * If this process has been taken out of the wait list, then we know
173  * that it has been signaled by ConditionVariableSignal (or
174  * ConditionVariableBroadcast), so we should return to the caller. But
175  * that doesn't guarantee that the exit condition is met, only that we
176  * ought to check it. So we must put the process back into the wait
177  * list, to ensure we don't miss any additional wakeup occurring while
178  * the caller checks its exit condition. We can take ourselves out of
179  * the wait list only when the caller calls
180  * ConditionVariableCancelSleep.
181  *
182  * If we're still in the wait list, then the latch must have been set
183  * by something other than ConditionVariableSignal; though we don't
184  * guarantee not to return spuriously, we'll avoid this obvious case.
185  */
186  SpinLockAcquire(&cv->mutex);
187  if (!proclist_contains(&cv->wakeup, MyProc->pgprocno, cvWaitLink))
188  {
189  done = true;
190  proclist_push_tail(&cv->wakeup, MyProc->pgprocno, cvWaitLink);
191  }
192  SpinLockRelease(&cv->mutex);
193  } while (!done);
194 }
195 
196 /*
197  * Cancel any pending sleep operation.
198  *
199  * We just need to remove ourselves from the wait queue of any condition
200  * variable for which we have previously prepared a sleep.
201  *
202  * Do nothing if nothing is pending; this allows this function to be called
203  * during transaction abort to clean up any unfinished CV sleep.
204  */
205 void
207 {
209 
210  if (cv == NULL)
211  return;
212 
213  SpinLockAcquire(&cv->mutex);
214  if (proclist_contains(&cv->wakeup, MyProc->pgprocno, cvWaitLink))
215  proclist_delete(&cv->wakeup, MyProc->pgprocno, cvWaitLink);
216  SpinLockRelease(&cv->mutex);
217 
218  cv_sleep_target = NULL;
219 }
220 
221 /*
222  * Wake up the oldest process sleeping on the CV, if there is any.
223  *
224  * Note: it's difficult to tell whether this has any real effect: we know
225  * whether we took an entry off the list, but the entry might only be a
226  * sentinel. Hence, think twice before proposing that this should return
227  * a flag telling whether it woke somebody.
228  */
229 void
231 {
232  PGPROC *proc = NULL;
233 
234  /* Remove the first process from the wakeup queue (if any). */
235  SpinLockAcquire(&cv->mutex);
236  if (!proclist_is_empty(&cv->wakeup))
237  proc = proclist_pop_head_node(&cv->wakeup, cvWaitLink);
238  SpinLockRelease(&cv->mutex);
239 
240  /* If we found someone sleeping, set their latch to wake them up. */
241  if (proc != NULL)
242  SetLatch(&proc->procLatch);
243 }
244 
245 /*
246  * Wake up all processes sleeping on the given CV.
247  *
248  * This guarantees to wake all processes that were sleeping on the CV
249  * at time of call, but processes that add themselves to the list mid-call
250  * will typically not get awakened.
251  */
252 void
254 {
255  int pgprocno = MyProc->pgprocno;
256  PGPROC *proc = NULL;
257  bool have_sentinel = false;
258 
259  /*
260  * In some use-cases, it is common for awakened processes to immediately
261  * re-queue themselves. If we just naively try to reduce the wakeup list
262  * to empty, we'll get into a potentially-indefinite loop against such a
263  * process. The semantics we really want are just to be sure that we have
264  * wakened all processes that were in the list at entry. We can use our
265  * own cvWaitLink as a sentinel to detect when we've finished.
266  *
267  * A seeming flaw in this approach is that someone else might signal the
268  * CV and in doing so remove our sentinel entry. But that's fine: since
269  * CV waiters are always added and removed in order, that must mean that
270  * every previous waiter has been wakened, so we're done. We'll get an
271  * extra "set" on our latch from the someone else's signal, which is
272  * slightly inefficient but harmless.
273  *
274  * We can't insert our cvWaitLink as a sentinel if it's already in use in
275  * some other proclist. While that's not expected to be true for typical
276  * uses of this function, we can deal with it by simply canceling any
277  * prepared CV sleep. The next call to ConditionVariableSleep will take
278  * care of re-establishing the lost state.
279  */
280  if (cv_sleep_target != NULL)
282 
283  /*
284  * Inspect the state of the queue. If it's empty, we have nothing to do.
285  * If there's exactly one entry, we need only remove and signal that
286  * entry. Otherwise, remove the first entry and insert our sentinel.
287  */
288  SpinLockAcquire(&cv->mutex);
289  /* While we're here, let's assert we're not in the list. */
290  Assert(!proclist_contains(&cv->wakeup, pgprocno, cvWaitLink));
291 
292  if (!proclist_is_empty(&cv->wakeup))
293  {
294  proc = proclist_pop_head_node(&cv->wakeup, cvWaitLink);
295  if (!proclist_is_empty(&cv->wakeup))
296  {
297  proclist_push_tail(&cv->wakeup, pgprocno, cvWaitLink);
298  have_sentinel = true;
299  }
300  }
301  SpinLockRelease(&cv->mutex);
302 
303  /* Awaken first waiter, if there was one. */
304  if (proc != NULL)
305  SetLatch(&proc->procLatch);
306 
307  while (have_sentinel)
308  {
309  /*
310  * Each time through the loop, remove the first wakeup list entry, and
311  * signal it unless it's our sentinel. Repeat as long as the sentinel
312  * remains in the list.
313  *
314  * Notice that if someone else removes our sentinel, we will waken one
315  * additional process before exiting. That's intentional, because if
316  * someone else signals the CV, they may be intending to waken some
317  * third process that added itself to the list after we added the
318  * sentinel. Better to give a spurious wakeup (which should be
319  * harmless beyond wasting some cycles) than to lose a wakeup.
320  */
321  proc = NULL;
322  SpinLockAcquire(&cv->mutex);
323  if (!proclist_is_empty(&cv->wakeup))
324  proc = proclist_pop_head_node(&cv->wakeup, cvWaitLink);
325  have_sentinel = proclist_contains(&cv->wakeup, pgprocno, cvWaitLink);
326  SpinLockRelease(&cv->mutex);
327 
328  if (proc != NULL && proc != MyProc)
329  SetLatch(&proc->procLatch);
330  }
331 }
int AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch, void *user_data)
Definition: latch.c:666
proclist_head wakeup
PGPROC * MyProc
Definition: proc.c:67
#define SpinLockInit(lock)
Definition: spin.h:60
static WaitEventSet * cv_wait_event_set
void ConditionVariableBroadcast(ConditionVariable *cv)
void ResetLatch(volatile Latch *latch)
Definition: latch.c:497
#define proclist_delete(list, procno, link_member)
Definition: proclist.h:187
Latch procLatch
Definition: proc.h:104
void ConditionVariablePrepareToSleep(ConditionVariable *cv)
WaitEventSet * CreateWaitEventSet(MemoryContext context, int nevents)
Definition: latch.c:520
#define SpinLockAcquire(lock)
Definition: spin.h:62
void ConditionVariableInit(ConditionVariable *cv)
void ConditionVariableCancelSleep(void)
uint32 events
Definition: latch.h:143
void ConditionVariableSignal(ConditionVariable *cv)
unsigned int uint32
Definition: c.h:325
MemoryContext TopMemoryContext
Definition: mcxt.c:44
#define SpinLockRelease(lock)
Definition: spin.h:64
#define WL_POSTMASTER_DEATH
Definition: latch.h:128
#define PGINVALID_SOCKET
Definition: port.h:33
static ConditionVariable * cv_sleep_target
#define proclist_pop_head_node(list, link_member)
Definition: proclist.h:193
void SetLatch(volatile Latch *latch)
Definition: latch.c:414
void ConditionVariableSleep(ConditionVariable *cv, uint32 wait_event_info)
#define Assert(condition)
Definition: c.h:699
static bool proclist_is_empty(proclist_head *list)
Definition: proclist.h:38
#define proclist_push_tail(list, procno, link_member)
Definition: proclist.h:191
int pgprocno
Definition: proc.h:110
static void proclist_init(proclist_head *list)
Definition: proclist.h:29
struct Latch * MyLatch
Definition: globals.c:55
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98
Definition: proc.h:95
#define WL_LATCH_SET
Definition: latch.h:124
int WaitEventSetWait(WaitEventSet *set, long timeout, WaitEvent *occurred_events, int nevents, uint32 wait_event_info)
Definition: latch.c:921
#define proclist_contains(list, procno, link_member)
Definition: proclist.h:195