GRPC Core  0.13.1-pre1
 All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
sync.h
Go to the documentation of this file.
1 /*
2  *
3  * Copyright 2016, Google Inc.
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are
8  * met:
9  *
10  * * Redistributions of source code must retain the above copyright
11  * notice, this list of conditions and the following disclaimer.
12  * * Redistributions in binary form must reproduce the above
13  * copyright notice, this list of conditions and the following disclaimer
14  * in the documentation and/or other materials provided with the
15  * distribution.
16  * * Neither the name of Google Inc. nor the names of its
17  * contributors may be used to endorse or promote products derived from
18  * this software without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  *
32  */
33 
34 #ifndef GRPC_IMPL_CODEGEN_SYNC_H
35 #define GRPC_IMPL_CODEGEN_SYNC_H
36 /* Synchronization primitives for GPR.
37 
38  The type gpr_mu provides a non-reentrant mutex (lock).
39 
40  The type gpr_cv provides a condition variable.
41 
42  The type gpr_once provides for one-time initialization.
43 
44  The type gpr_event provides one-time-setting, reading, and
45  waiting of a void*, with memory barriers.
46 
47  The type gpr_refcount provides an object reference counter,
48  with memory barriers suitable to control
49  object lifetimes.
50 
51  The type gpr_stats_counter provides an atomic statistics counter. It
52  provides no memory barriers.
53  */
54 
55 /* Platform-specific type declarations of gpr_mu and gpr_cv. */
58 
59 #if defined(GPR_POSIX_SYNC)
61 #elif defined(GPR_WIN32)
63 #elif !defined(GPR_CUSTOM_SYNC)
64 #error Unable to determine platform for sync
65 #endif
66 
67 #include <grpc/impl/codegen/time.h> /* for gpr_timespec */
68 
69 #ifdef __cplusplus
70 extern "C" {
71 #endif
72 
73 /* --- Mutex interface ---
74 
75  At most one thread may hold an exclusive lock on a mutex at any given time.
76  Actions taken by a thread that holds a mutex exclusively happen after
77  actions taken by all previous holders of the mutex. Variables of type
78  gpr_mu are uninitialized when first declared. */
79 
80 /* Initialize *mu. Requires: *mu uninitialized. */
81 GPRAPI void gpr_mu_init(gpr_mu *mu);
82 
83 /* Cause *mu no longer to be initialized, freeing any memory in use. Requires:
84  *mu initialized; no other concurrent operation on *mu. */
85 GPRAPI void gpr_mu_destroy(gpr_mu *mu);
86 
87 /* Wait until no thread has a lock on *mu, cause the calling thread to own an
88  exclusive lock on *mu, then return. May block indefinitely or crash if the
89  calling thread has a lock on *mu. Requires: *mu initialized. */
90 GPRAPI void gpr_mu_lock(gpr_mu *mu);
91 
92 /* Release an exclusive lock on *mu held by the calling thread. Requires: *mu
93  initialized; the calling thread holds an exclusive lock on *mu. */
94 GPRAPI void gpr_mu_unlock(gpr_mu *mu);
95 
96 /* Without blocking, attempt to acquire an exclusive lock on *mu for the
97  calling thread, then return non-zero iff success. Fail, if any thread holds
98  the lock; succeeds with high probability if no thread holds the lock.
99  Requires: *mu initialized. */
100 GPRAPI int gpr_mu_trylock(gpr_mu *mu);
101 
102 /* --- Condition variable interface ---
103 
104  A while-loop should be used with gpr_cv_wait() when waiting for conditions
105  to become true. See the example below. Variables of type gpr_cv are
106  uninitialized when first declared. */
107 
108 /* Initialize *cv. Requires: *cv uninitialized. */
109 GPRAPI void gpr_cv_init(gpr_cv *cv);
110 
111 /* Cause *cv no longer to be initialized, freeing any memory in use. Requires:
112  *cv initialized; no other concurrent operation on *cv.*/
113 GPRAPI void gpr_cv_destroy(gpr_cv *cv);
114 
115 /* Atomically release *mu and wait on *cv. When the calling thread is woken
116  from *cv or the deadline abs_deadline is exceeded, execute gpr_mu_lock(mu)
117  and return whether the deadline was exceeded. Use
118  abs_deadline==gpr_inf_future for no deadline. abs_deadline can be either
119  an absolute deadline, or a GPR_TIMESPAN. May return even when not
120  woken explicitly. Requires: *mu and *cv initialized; the calling thread
121  holds an exclusive lock on *mu. */
122 GPRAPI int gpr_cv_wait(gpr_cv *cv, gpr_mu *mu, gpr_timespec abs_deadline);
123 
124 /* If any threads are waiting on *cv, wake at least one.
125  Clients may treat this as an optimization of gpr_cv_broadcast()
126  for use in the case where waking more than one waiter is not useful.
127  Requires: *cv initialized. */
128 GPRAPI void gpr_cv_signal(gpr_cv *cv);
129 
130 /* Wake all threads waiting on *cv. Requires: *cv initialized. */
131 GPRAPI void gpr_cv_broadcast(gpr_cv *cv);
132 
133 /* --- One-time initialization ---
134 
135  gpr_once must be declared with static storage class, and initialized with
136  GPR_ONCE_INIT. e.g.,
137  static gpr_once once_var = GPR_ONCE_INIT; */
138 
139 /* Ensure that (*init_routine)() has been called exactly once (for the
140  specified gpr_once instance) and then return.
141  If multiple threads call gpr_once() on the same gpr_once instance, one of
142  them will call (*init_routine)(), and the others will block until that call
143  finishes.*/
144 GPRAPI void gpr_once_init(gpr_once *once, void (*init_routine)(void));
145 
146 /* --- One-time event notification ---
147 
148  These operations act on a gpr_event, which should be initialized with
149  gpr_ev_init(), or with GPR_EVENT_INIT if static, e.g.,
150  static gpr_event event_var = GPR_EVENT_INIT;
151  It requires no destruction. */
152 
153 /* Initialize *ev. */
155 
156 /* Set *ev so that gpr_event_get() and gpr_event_wait() will return value.
157  Requires: *ev initialized; value != NULL; no prior or concurrent calls to
158  gpr_event_set(ev, ...) since initialization. */
159 GPRAPI void gpr_event_set(gpr_event *ev, void *value);
160 
161 /* Return the value set by gpr_event_set(ev, ...), or NULL if no such call has
162  completed. If the result is non-NULL, all operations that occurred prior to
163  the gpr_event_set(ev, ...) set will be visible after this call returns.
164  Requires: *ev initialized. This operation is faster than acquiring a mutex
165  on most platforms. */
166 GPRAPI void *gpr_event_get(gpr_event *ev);
167 
168 /* Wait until *ev is set by gpr_event_set(ev, ...), or abs_deadline is
169  exceeded, then return gpr_event_get(ev). Requires: *ev initialized. Use
170  abs_deadline==gpr_inf_future for no deadline. When the event has been
171  signalled before the call, this operation is faster than acquiring a mutex
172  on most platforms. */
173 GPRAPI void *gpr_event_wait(gpr_event *ev, gpr_timespec abs_deadline);
174 
175 /* --- Reference counting ---
176 
177  These calls act on the type gpr_refcount. It requires no destruction. */
178 
179 /* Initialize *r to value n. */
180 GPRAPI void gpr_ref_init(gpr_refcount *r, int n);
181 
182 /* Increment the reference count *r. Requires *r initialized. */
183 GPRAPI void gpr_ref(gpr_refcount *r);
184 
185 /* Increment the reference count *r by n. Requires *r initialized, n > 0. */
186 GPRAPI void gpr_refn(gpr_refcount *r, int n);
187 
188 /* Decrement the reference count *r and return non-zero iff it has reached
189  zero. . Requires *r initialized. */
191 
192 /* --- Stats counters ---
193 
194  These calls act on the integral type gpr_stats_counter. It requires no
195  destruction. Static instances may be initialized with
196  gpr_stats_counter c = GPR_STATS_INIT;
197  Beware: These operations do not imply memory barriers. Do not use them to
198  synchronize other events. */
199 
200 /* Initialize *c to the value n. */
201 GPRAPI void gpr_stats_init(gpr_stats_counter *c, intptr_t n);
202 
203 /* *c += inc. Requires: *c initialized. */
204 GPRAPI void gpr_stats_inc(gpr_stats_counter *c, intptr_t inc);
205 
206 /* Return *c. Requires: *c initialized. */
207 GPRAPI intptr_t gpr_stats_read(const gpr_stats_counter *c);
208 
209 /* ==================Example use of interface===================
210  A producer-consumer queue of up to N integers,
211  illustrating the use of the calls in this interface. */
212 #if 0
213 
214 #define N 4
215 
216  typedef struct queue {
217  gpr_cv non_empty; /* Signalled when length becomes non-zero. */
218  gpr_cv non_full; /* Signalled when length becomes non-N. */
219  gpr_mu mu; /* Protects all fields below.
220  (That is, except during initialization or
221  destruction, the fields below should be accessed
222  only by a thread that holds mu.) */
223  int head; /* Index of head of queue 0..N-1. */
224  int length; /* Number of valid elements in queue 0..N. */
225  int elem[N]; /* elem[head .. head+length-1] are queue elements. */
226  } queue;
227 
228  /* Initialize *q. */
229  void queue_init(queue *q) {
230  gpr_mu_init(&q->mu);
231  gpr_cv_init(&q->non_empty);
232  gpr_cv_init(&q->non_full);
233  q->head = 0;
234  q->length = 0;
235  }
236 
237  /* Free storage associated with *q. */
238  void queue_destroy(queue *q) {
239  gpr_mu_destroy(&q->mu);
240  gpr_cv_destroy(&q->non_empty);
241  gpr_cv_destroy(&q->non_full);
242  }
243 
244  /* Wait until there is room in *q, then append x to *q. */
245  void queue_append(queue *q, int x) {
246  gpr_mu_lock(&q->mu);
247  /* To wait for a predicate without a deadline, loop on the negation of the
248  predicate, and use gpr_cv_wait(..., gpr_inf_future) inside the loop
249  to release the lock, wait, and reacquire on each iteration. Code that
250  makes the condition true should use gpr_cv_broadcast() on the
251  corresponding condition variable. The predicate must be on state
252  protected by the lock. */
253  while (q->length == N) {
254  gpr_cv_wait(&q->non_full, &q->mu, gpr_inf_future);
255  }
256  if (q->length == 0) { /* Wake threads blocked in queue_remove(). */
257  /* It's normal to use gpr_cv_broadcast() or gpr_signal() while
258  holding the lock. */
259  gpr_cv_broadcast(&q->non_empty);
260  }
261  q->elem[(q->head + q->length) % N] = x;
262  q->length++;
263  gpr_mu_unlock(&q->mu);
264  }
265 
266  /* If it can be done without blocking, append x to *q and return non-zero.
267  Otherwise return 0. */
268  int queue_try_append(queue *q, int x) {
269  int result = 0;
270  if (gpr_mu_trylock(&q->mu)) {
271  if (q->length != N) {
272  if (q->length == 0) { /* Wake threads blocked in queue_remove(). */
273  gpr_cv_broadcast(&q->non_empty);
274  }
275  q->elem[(q->head + q->length) % N] = x;
276  q->length++;
277  result = 1;
278  }
279  gpr_mu_unlock(&q->mu);
280  }
281  return result;
282  }
283 
284  /* Wait until the *q is non-empty or deadline abs_deadline passes. If the
285  queue is non-empty, remove its head entry, place it in *head, and return
286  non-zero. Otherwise return 0. */
287  int queue_remove(queue *q, int *head, gpr_timespec abs_deadline) {
288  int result = 0;
289  gpr_mu_lock(&q->mu);
290  /* To wait for a predicate with a deadline, loop on the negation of the
291  predicate or until gpr_cv_wait() returns true. Code that makes
292  the condition true should use gpr_cv_broadcast() on the corresponding
293  condition variable. The predicate must be on state protected by the
294  lock. */
295  while (q->length == 0 &&
296  !gpr_cv_wait(&q->non_empty, &q->mu, abs_deadline)) {
297  }
298  if (q->length != 0) { /* Queue is non-empty. */
299  result = 1;
300  if (q->length == N) { /* Wake threads blocked in queue_append(). */
301  gpr_cv_broadcast(&q->non_full);
302  }
303  *head = q->elem[q->head];
304  q->head = (q->head + 1) % N;
305  q->length--;
306  } /* else deadline exceeded */
307  gpr_mu_unlock(&q->mu);
308  return result;
309  }
310 #endif /* 0 */
311 
312 #ifdef __cplusplus
313 }
314 #endif
315 
316 #endif /* GRPC_IMPL_CODEGEN_SYNC_H */
GPRAPI void * gpr_event_get(gpr_event *ev)
GPRAPI void gpr_event_set(gpr_event *ev, void *value)
Definition: sync_generic.h:47
GPRAPI intptr_t gpr_stats_read(const gpr_stats_counter *c)
GPRAPI gpr_timespec gpr_inf_future(gpr_clock_type type)
GPRAPI void gpr_stats_init(gpr_stats_counter *c, intptr_t n)
#define GPRAPI
Definition: port_platform.h:359
GPRAPI int gpr_mu_trylock(gpr_mu *mu)
GPRAPI void gpr_cv_destroy(gpr_cv *cv)
pthread_once_t gpr_once
Definition: sync_posix.h:43
GPRAPI void gpr_mu_destroy(gpr_mu *mu)
GPRAPI void gpr_mu_unlock(gpr_mu *mu)
GPRAPI void gpr_cv_signal(gpr_cv *cv)
GPRAPI void gpr_event_init(gpr_event *ev)
Definition: sync_generic.h:50
pthread_cond_t gpr_cv
Definition: sync_posix.h:42
GPRAPI void gpr_once_init(gpr_once *once, void(*init_routine)(void))
Definition: sync_win32.h:39
GPRAPI void gpr_mu_lock(gpr_mu *mu)
GPRAPI void gpr_ref_init(gpr_refcount *r, int n)
GPRAPI int gpr_cv_wait(gpr_cv *cv, gpr_mu *mu, gpr_timespec abs_deadline)
GPRAPI void gpr_stats_inc(gpr_stats_counter *c, intptr_t inc)
GPRAPI int gpr_unref(gpr_refcount *r)
GPRAPI void gpr_cv_broadcast(gpr_cv *cv)
GPRAPI void gpr_cv_init(gpr_cv *cv)
GPRAPI void gpr_ref(gpr_refcount *r)
GPRAPI void gpr_mu_init(gpr_mu *mu)
Definition: time.h:63
GPRAPI void gpr_refn(gpr_refcount *r, int n)
GPRAPI void * gpr_event_wait(gpr_event *ev, gpr_timespec abs_deadline)
Definition: sync_generic.h:41