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

source code of include/grpc/support/sync.h