sync.h 11 KB

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