GRPC Core  3.0.0-dev
 All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
sync.h
Go to the documentation of this file.
1 /*
2  *
3  * Copyright 2015, 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_SUPPORT_SYNC_H
35 #define GRPC_SUPPORT_SYNC_H
36 
37 #include <grpc/impl/codegen/gpr_types.h> /* for gpr_timespec */
38 #include <grpc/impl/codegen/sync.h>
39 
40 #ifdef __cplusplus
41 extern "C" {
42 #endif
43 
44 /* --- Mutex interface ---
45 
46  At most one thread may hold an exclusive lock on a mutex at any given time.
47  Actions taken by a thread that holds a mutex exclusively happen after
48  actions taken by all previous holders of the mutex. Variables of type
49  gpr_mu are uninitialized when first declared. */
50 
51 /* Initialize *mu. Requires: *mu uninitialized. */
52 GPRAPI void gpr_mu_init(gpr_mu *mu);
53 
54 /* Cause *mu no longer to be initialized, freeing any memory in use. Requires:
55  *mu initialized; no other concurrent operation on *mu. */
56 GPRAPI void gpr_mu_destroy(gpr_mu *mu);
57 
58 /* Wait until no thread has a lock on *mu, cause the calling thread to own an
59  exclusive lock on *mu, then return. May block indefinitely or crash if the
60  calling thread has a lock on *mu. Requires: *mu initialized. */
61 GPRAPI void gpr_mu_lock(gpr_mu *mu);
62 
63 /* Release an exclusive lock on *mu held by the calling thread. Requires: *mu
64  initialized; the calling thread holds an exclusive lock on *mu. */
65 GPRAPI void gpr_mu_unlock(gpr_mu *mu);
66 
67 /* Without blocking, attempt to acquire an exclusive lock on *mu for the
68  calling thread, then return non-zero iff success. Fail, if any thread holds
69  the lock; succeeds with high probability if no thread holds the lock.
70  Requires: *mu initialized. */
72 
73 /* --- Condition variable interface ---
74 
75  A while-loop should be used with gpr_cv_wait() when waiting for conditions
76  to become true. See the example below. Variables of type gpr_cv are
77  uninitialized when first declared. */
78 
79 /* Initialize *cv. Requires: *cv uninitialized. */
80 GPRAPI void gpr_cv_init(gpr_cv *cv);
81 
82 /* Cause *cv no longer to be initialized, freeing any memory in use. Requires:
83  *cv initialized; no other concurrent operation on *cv.*/
84 GPRAPI void gpr_cv_destroy(gpr_cv *cv);
85 
86 /* Atomically release *mu and wait on *cv. When the calling thread is woken
87  from *cv or the deadline abs_deadline is exceeded, execute gpr_mu_lock(mu)
88  and return whether the deadline was exceeded. Use
89  abs_deadline==gpr_inf_future for no deadline. abs_deadline can be either
90  an absolute deadline, or a GPR_TIMESPAN. May return even when not
91  woken explicitly. Requires: *mu and *cv initialized; the calling thread
92  holds an exclusive lock on *mu. */
93 GPRAPI int gpr_cv_wait(gpr_cv *cv, gpr_mu *mu, gpr_timespec abs_deadline);
94 
95 /* If any threads are waiting on *cv, wake at least one.
96  Clients may treat this as an optimization of gpr_cv_broadcast()
97  for use in the case where waking more than one waiter is not useful.
98  Requires: *cv initialized. */
99 GPRAPI void gpr_cv_signal(gpr_cv *cv);
100 
101 /* Wake all threads waiting on *cv. Requires: *cv initialized. */
102 GPRAPI void gpr_cv_broadcast(gpr_cv *cv);
103 
104 /* --- One-time initialization ---
105 
106  gpr_once must be declared with static storage class, and initialized with
107  GPR_ONCE_INIT. e.g.,
108  static gpr_once once_var = GPR_ONCE_INIT; */
109 
110 /* Ensure that (*init_routine)() has been called exactly once (for the
111  specified gpr_once instance) and then return.
112  If multiple threads call gpr_once() on the same gpr_once instance, one of
113  them will call (*init_routine)(), and the others will block until that call
114  finishes.*/
115 GPRAPI void gpr_once_init(gpr_once *once, void (*init_routine)(void));
116 
117 /* --- One-time event notification ---
118 
119  These operations act on a gpr_event, which should be initialized with
120  gpr_ev_init(), or with GPR_EVENT_INIT if static, e.g.,
121  static gpr_event event_var = GPR_EVENT_INIT;
122  It requires no destruction. */
123 
124 /* Initialize *ev. */
126 
127 /* Set *ev so that gpr_event_get() and gpr_event_wait() will return value.
128  Requires: *ev initialized; value != NULL; no prior or concurrent calls to
129  gpr_event_set(ev, ...) since initialization. */
130 GPRAPI void gpr_event_set(gpr_event *ev, void *value);
131 
132 /* Return the value set by gpr_event_set(ev, ...), or NULL if no such call has
133  completed. If the result is non-NULL, all operations that occurred prior to
134  the gpr_event_set(ev, ...) set will be visible after this call returns.
135  Requires: *ev initialized. This operation is faster than acquiring a mutex
136  on most platforms. */
137 GPRAPI void *gpr_event_get(gpr_event *ev);
138 
139 /* Wait until *ev is set by gpr_event_set(ev, ...), or abs_deadline is
140  exceeded, then return gpr_event_get(ev). Requires: *ev initialized. Use
141  abs_deadline==gpr_inf_future for no deadline. When the event has been
142  signalled before the call, this operation is faster than acquiring a mutex
143  on most platforms. */
144 GPRAPI void *gpr_event_wait(gpr_event *ev, gpr_timespec abs_deadline);
145 
146 /* --- Reference counting ---
147 
148  These calls act on the type gpr_refcount. It requires no destruction. */
149 
150 /* Initialize *r to value n. */
151 GPRAPI void gpr_ref_init(gpr_refcount *r, int n);
152 
153 /* Increment the reference count *r. Requires *r initialized. */
154 GPRAPI void gpr_ref(gpr_refcount *r);
155 
156 /* Increment the reference count *r. Requires *r initialized.
157  Crashes if refcount is zero */
159 
160 /* Increment the reference count *r by n. Requires *r initialized, n > 0. */
161 GPRAPI void gpr_refn(gpr_refcount *r, int n);
162 
163 /* Decrement the reference count *r and return non-zero iff it has reached
164  zero. . Requires *r initialized. */
166 
167 /* --- Stats counters ---
168 
169  These calls act on the integral type gpr_stats_counter. It requires no
170  destruction. Static instances may be initialized with
171  gpr_stats_counter c = GPR_STATS_INIT;
172  Beware: These operations do not imply memory barriers. Do not use them to
173  synchronize other events. */
174 
175 /* Initialize *c to the value n. */
176 GPRAPI void gpr_stats_init(gpr_stats_counter *c, intptr_t n);
177 
178 /* *c += inc. Requires: *c initialized. */
179 GPRAPI void gpr_stats_inc(gpr_stats_counter *c, intptr_t inc);
180 
181 /* Return *c. Requires: *c initialized. */
182 GPRAPI intptr_t gpr_stats_read(const gpr_stats_counter *c);
183 
184 /* ==================Example use of interface===================
185  A producer-consumer queue of up to N integers,
186  illustrating the use of the calls in this interface. */
187 #if 0
188 
189 #define N 4
190 
191  typedef struct queue {
192  gpr_cv non_empty; /* Signalled when length becomes non-zero. */
193  gpr_cv non_full; /* Signalled when length becomes non-N. */
194  gpr_mu mu; /* Protects all fields below.
195  (That is, except during initialization or
196  destruction, the fields below should be accessed
197  only by a thread that holds mu.) */
198  int head; /* Index of head of queue 0..N-1. */
199  int length; /* Number of valid elements in queue 0..N. */
200  int elem[N]; /* elem[head .. head+length-1] are queue elements. */
201  } queue;
202 
203  /* Initialize *q. */
204  void queue_init(queue *q) {
205  gpr_mu_init(&q->mu);
206  gpr_cv_init(&q->non_empty);
207  gpr_cv_init(&q->non_full);
208  q->head = 0;
209  q->length = 0;
210  }
211 
212  /* Free storage associated with *q. */
213  void queue_destroy(queue *q) {
214  gpr_mu_destroy(&q->mu);
215  gpr_cv_destroy(&q->non_empty);
216  gpr_cv_destroy(&q->non_full);
217  }
218 
219  /* Wait until there is room in *q, then append x to *q. */
220  void queue_append(queue *q, int x) {
221  gpr_mu_lock(&q->mu);
222  /* To wait for a predicate without a deadline, loop on the negation of the
223  predicate, and use gpr_cv_wait(..., gpr_inf_future) inside the loop
224  to release the lock, wait, and reacquire on each iteration. Code that
225  makes the condition true should use gpr_cv_broadcast() on the
226  corresponding condition variable. The predicate must be on state
227  protected by the lock. */
228  while (q->length == N) {
229  gpr_cv_wait(&q->non_full, &q->mu, gpr_inf_future);
230  }
231  if (q->length == 0) { /* Wake threads blocked in queue_remove(). */
232  /* It's normal to use gpr_cv_broadcast() or gpr_signal() while
233  holding the lock. */
234  gpr_cv_broadcast(&q->non_empty);
235  }
236  q->elem[(q->head + q->length) % N] = x;
237  q->length++;
238  gpr_mu_unlock(&q->mu);
239  }
240 
241  /* If it can be done without blocking, append x to *q and return non-zero.
242  Otherwise return 0. */
243  int queue_try_append(queue *q, int x) {
244  int result = 0;
245  if (gpr_mu_trylock(&q->mu)) {
246  if (q->length != N) {
247  if (q->length == 0) { /* Wake threads blocked in queue_remove(). */
248  gpr_cv_broadcast(&q->non_empty);
249  }
250  q->elem[(q->head + q->length) % N] = x;
251  q->length++;
252  result = 1;
253  }
254  gpr_mu_unlock(&q->mu);
255  }
256  return result;
257  }
258 
259  /* Wait until the *q is non-empty or deadline abs_deadline passes. If the
260  queue is non-empty, remove its head entry, place it in *head, and return
261  non-zero. Otherwise return 0. */
262  int queue_remove(queue *q, int *head, gpr_timespec abs_deadline) {
263  int result = 0;
264  gpr_mu_lock(&q->mu);
265  /* To wait for a predicate with a deadline, loop on the negation of the
266  predicate or until gpr_cv_wait() returns true. Code that makes
267  the condition true should use gpr_cv_broadcast() on the corresponding
268  condition variable. The predicate must be on state protected by the
269  lock. */
270  while (q->length == 0 &&
271  !gpr_cv_wait(&q->non_empty, &q->mu, abs_deadline)) {
272  }
273  if (q->length != 0) { /* Queue is non-empty. */
274  result = 1;
275  if (q->length == N) { /* Wake threads blocked in queue_append(). */
276  gpr_cv_broadcast(&q->non_full);
277  }
278  *head = q->elem[q->head];
279  q->head = (q->head + 1) % N;
280  q->length--;
281  } /* else deadline exceeded */
282  gpr_mu_unlock(&q->mu);
283  return result;
284  }
285 #endif /* 0 */
286 
287 #ifdef __cplusplus
288 }
289 #endif
290 
291 #endif /* GRPC_SUPPORT_SYNC_H */
GPRAPI void gpr_stats_init(gpr_stats_counter *c, intptr_t n)
GPRAPI int gpr_cv_wait(gpr_cv *cv, gpr_mu *mu, gpr_timespec abs_deadline)
GPRAPI void gpr_event_init(gpr_event *ev)
Definition: sync_generic.h:47
#define GPRAPI
Definition: port_platform.h:396
pthread_once_t gpr_once
Definition: sync_posix.h:43
GPRAPI void gpr_cv_destroy(gpr_cv *cv)
GPRAPI void gpr_mu_init(gpr_mu *mu)
GPRAPI intptr_t gpr_stats_read(const gpr_stats_counter *c)
GPRAPI void gpr_cv_broadcast(gpr_cv *cv)
Definition: sync_generic.h:50
GPRAPI void gpr_stats_inc(gpr_stats_counter *c, intptr_t inc)
pthread_cond_t gpr_cv
Definition: sync_posix.h:42
GPRAPI void gpr_ref_init(gpr_refcount *r, int n)
Definition: sync_windows.h:39
GPRAPI int gpr_mu_trylock(gpr_mu *mu)
GPRAPI void gpr_event_set(gpr_event *ev, void *value)
GPRAPI void gpr_cv_init(gpr_cv *cv)
GPRAPI void gpr_ref_non_zero(gpr_refcount *r)
GPRAPI void * gpr_event_get(gpr_event *ev)
GPRAPI gpr_timespec gpr_inf_future(gpr_clock_type type)
GPRAPI void gpr_mu_lock(gpr_mu *mu)
GPRAPI void gpr_once_init(gpr_once *once, void(*init_routine)(void))
Definition: gpr_types.h:63
GPRAPI void gpr_mu_unlock(gpr_mu *mu)
GPRAPI void gpr_ref(gpr_refcount *r)
GPRAPI void gpr_cv_signal(gpr_cv *cv)
GPRAPI void gpr_refn(gpr_refcount *r, int n)
Definition: sync_generic.h:41
GPRAPI void gpr_mu_destroy(gpr_mu *mu)
GPRAPI void * gpr_event_wait(gpr_event *ev, gpr_timespec abs_deadline)
GPRAPI int gpr_unref(gpr_refcount *r)