sync_test.cc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  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. /* Test of gpr synchronization support. */
  19. #include <grpc/support/alloc.h>
  20. #include <grpc/support/log.h>
  21. #include <grpc/support/sync.h>
  22. #include <grpc/support/time.h>
  23. #include <stdio.h>
  24. #include <stdlib.h>
  25. #include "src/core/lib/gpr/thd.h"
  26. #include "test/core/util/test_config.h"
  27. /* ==================Example use of interface===================
  28. A producer-consumer queue of up to N integers,
  29. illustrating the use of the calls in this interface. */
  30. #define N 4
  31. typedef struct queue {
  32. gpr_cv non_empty; /* Signalled when length becomes non-zero. */
  33. gpr_cv non_full; /* Signalled when length becomes non-N. */
  34. gpr_mu mu; /* Protects all fields below.
  35. (That is, except during initialization or
  36. destruction, the fields below should be accessed
  37. only by a thread that holds mu.) */
  38. int head; /* Index of head of queue 0..N-1. */
  39. int length; /* Number of valid elements in queue 0..N. */
  40. int elem[N]; /* elem[head .. head+length-1] are queue elements. */
  41. } queue;
  42. /* Initialize *q. */
  43. void queue_init(queue* q) {
  44. gpr_mu_init(&q->mu);
  45. gpr_cv_init(&q->non_empty);
  46. gpr_cv_init(&q->non_full);
  47. q->head = 0;
  48. q->length = 0;
  49. }
  50. /* Free storage associated with *q. */
  51. void queue_destroy(queue* q) {
  52. gpr_mu_destroy(&q->mu);
  53. gpr_cv_destroy(&q->non_empty);
  54. gpr_cv_destroy(&q->non_full);
  55. }
  56. /* Wait until there is room in *q, then append x to *q. */
  57. void queue_append(queue* q, int x) {
  58. gpr_mu_lock(&q->mu);
  59. /* To wait for a predicate without a deadline, loop on the negation of the
  60. predicate, and use gpr_cv_wait(..., gpr_inf_future(GPR_CLOCK_REALTIME))
  61. inside the loop
  62. to release the lock, wait, and reacquire on each iteration. Code that
  63. makes the condition true should use gpr_cv_broadcast() on the
  64. corresponding condition variable. The predicate must be on state
  65. protected by the lock. */
  66. while (q->length == N) {
  67. gpr_cv_wait(&q->non_full, &q->mu, gpr_inf_future(GPR_CLOCK_MONOTONIC));
  68. }
  69. if (q->length == 0) { /* Wake threads blocked in queue_remove(). */
  70. /* It's normal to use gpr_cv_broadcast() or gpr_signal() while
  71. holding the lock. */
  72. gpr_cv_broadcast(&q->non_empty);
  73. }
  74. q->elem[(q->head + q->length) % N] = x;
  75. q->length++;
  76. gpr_mu_unlock(&q->mu);
  77. }
  78. /* If it can be done without blocking, append x to *q and return non-zero.
  79. Otherwise return 0. */
  80. int queue_try_append(queue* q, int x) {
  81. int result = 0;
  82. if (gpr_mu_trylock(&q->mu)) {
  83. if (q->length != N) {
  84. if (q->length == 0) { /* Wake threads blocked in queue_remove(). */
  85. gpr_cv_broadcast(&q->non_empty);
  86. }
  87. q->elem[(q->head + q->length) % N] = x;
  88. q->length++;
  89. result = 1;
  90. }
  91. gpr_mu_unlock(&q->mu);
  92. }
  93. return result;
  94. }
  95. /* Wait until the *q is non-empty or deadline abs_deadline passes. If the
  96. queue is non-empty, remove its head entry, place it in *head, and return
  97. non-zero. Otherwise return 0. */
  98. int queue_remove(queue* q, int* head, gpr_timespec abs_deadline) {
  99. int result = 0;
  100. gpr_mu_lock(&q->mu);
  101. /* To wait for a predicate with a deadline, loop on the negation of the
  102. predicate or until gpr_cv_wait() returns true. Code that makes
  103. the condition true should use gpr_cv_broadcast() on the corresponding
  104. condition variable. The predicate must be on state protected by the
  105. lock. */
  106. while (q->length == 0 && !gpr_cv_wait(&q->non_empty, &q->mu, abs_deadline)) {
  107. }
  108. if (q->length != 0) { /* Queue is non-empty. */
  109. result = 1;
  110. if (q->length == N) { /* Wake threads blocked in queue_append(). */
  111. gpr_cv_broadcast(&q->non_full);
  112. }
  113. *head = q->elem[q->head];
  114. q->head = (q->head + 1) % N;
  115. q->length--;
  116. } /* else deadline exceeded */
  117. gpr_mu_unlock(&q->mu);
  118. return result;
  119. }
  120. /* ------------------------------------------------- */
  121. /* Tests for gpr_mu and gpr_cv, and the queue example. */
  122. struct test {
  123. int threads; /* number of threads */
  124. gpr_thd_id* thread_ids;
  125. int64_t iterations; /* number of iterations per thread */
  126. int64_t counter;
  127. int thread_count; /* used to allocate thread ids */
  128. int done; /* threads not yet completed */
  129. int incr_step; /* how much to increment/decrement refcount each time */
  130. gpr_mu mu; /* protects iterations, counter, thread_count, done */
  131. gpr_cv cv; /* signalling depends on test */
  132. gpr_cv done_cv; /* signalled when done == 0 */
  133. queue q;
  134. gpr_stats_counter stats_counter;
  135. gpr_refcount refcount;
  136. gpr_refcount thread_refcount;
  137. gpr_event event;
  138. };
  139. /* Return pointer to a new struct test. */
  140. static struct test* test_new(int threads, int64_t iterations, int incr_step) {
  141. struct test* m = static_cast<struct test*>(gpr_malloc(sizeof(*m)));
  142. m->threads = threads;
  143. m->thread_ids =
  144. static_cast<gpr_thd_id*>(gpr_malloc(sizeof(*m->thread_ids) * threads));
  145. m->iterations = iterations;
  146. m->counter = 0;
  147. m->thread_count = 0;
  148. m->done = threads;
  149. m->incr_step = incr_step;
  150. gpr_mu_init(&m->mu);
  151. gpr_cv_init(&m->cv);
  152. gpr_cv_init(&m->done_cv);
  153. queue_init(&m->q);
  154. gpr_stats_init(&m->stats_counter, 0);
  155. gpr_ref_init(&m->refcount, 0);
  156. gpr_ref_init(&m->thread_refcount, threads);
  157. gpr_event_init(&m->event);
  158. return m;
  159. }
  160. /* Return pointer to a new struct test. */
  161. static void test_destroy(struct test* m) {
  162. gpr_mu_destroy(&m->mu);
  163. gpr_cv_destroy(&m->cv);
  164. gpr_cv_destroy(&m->done_cv);
  165. queue_destroy(&m->q);
  166. gpr_free(m->thread_ids);
  167. gpr_free(m);
  168. }
  169. /* Create m->threads threads, each running (*body)(m) */
  170. static void test_create_threads(struct test* m, void (*body)(void* arg)) {
  171. int i;
  172. for (i = 0; i != m->threads; i++) {
  173. GPR_ASSERT(gpr_thd_new(&m->thread_ids[i], "grpc_create_threads", body, m));
  174. }
  175. }
  176. /* Wait until all threads report done. */
  177. static void test_wait(struct test* m) {
  178. gpr_mu_lock(&m->mu);
  179. while (m->done != 0) {
  180. gpr_cv_wait(&m->done_cv, &m->mu, gpr_inf_future(GPR_CLOCK_MONOTONIC));
  181. }
  182. gpr_mu_unlock(&m->mu);
  183. for (int i = 0; i != m->threads; i++) {
  184. gpr_thd_join(m->thread_ids[i]);
  185. }
  186. }
  187. /* Get an integer thread id in the raneg 0..threads-1 */
  188. static int thread_id(struct test* m) {
  189. int id;
  190. gpr_mu_lock(&m->mu);
  191. id = m->thread_count++;
  192. gpr_mu_unlock(&m->mu);
  193. return id;
  194. }
  195. /* Indicate that a thread is done, by decrementing m->done
  196. and signalling done_cv if m->done==0. */
  197. static void mark_thread_done(struct test* m) {
  198. gpr_mu_lock(&m->mu);
  199. GPR_ASSERT(m->done != 0);
  200. m->done--;
  201. if (m->done == 0) {
  202. gpr_cv_signal(&m->done_cv);
  203. }
  204. gpr_mu_unlock(&m->mu);
  205. }
  206. /* Test several threads running (*body)(struct test *m) for increasing settings
  207. of m->iterations, until about timeout_s to 2*timeout_s seconds have elapsed.
  208. If extra!=NULL, run (*extra)(m) in an additional thread.
  209. incr_step controls by how much m->refcount should be incremented/decremented
  210. (if at all) each time in the tests.
  211. */
  212. static void test(const char* name, void (*body)(void* m),
  213. void (*extra)(void* m), int timeout_s, int incr_step) {
  214. int64_t iterations = 256;
  215. struct test* m;
  216. gpr_timespec start = gpr_now(GPR_CLOCK_REALTIME);
  217. gpr_timespec time_taken;
  218. gpr_timespec deadline = gpr_time_add(
  219. start, gpr_time_from_micros(static_cast<int64_t>(timeout_s) * 1000000,
  220. GPR_TIMESPAN));
  221. fprintf(stderr, "%s:", name);
  222. fflush(stderr);
  223. while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0) {
  224. fprintf(stderr, " %ld", static_cast<long>(iterations));
  225. fflush(stderr);
  226. m = test_new(10, iterations, incr_step);
  227. gpr_thd_id extra_id;
  228. if (extra != nullptr) {
  229. GPR_ASSERT(gpr_thd_new(&extra_id, name, extra, m));
  230. m->done++; /* one more thread to wait for */
  231. }
  232. test_create_threads(m, body);
  233. test_wait(m);
  234. if (extra != nullptr) {
  235. gpr_thd_join(extra_id);
  236. }
  237. if (m->counter != m->threads * m->iterations * m->incr_step) {
  238. fprintf(stderr, "counter %ld threads %d iterations %ld\n",
  239. static_cast<long>(m->counter), m->threads,
  240. static_cast<long>(m->iterations));
  241. fflush(stderr);
  242. GPR_ASSERT(0);
  243. }
  244. test_destroy(m);
  245. iterations <<= 1;
  246. }
  247. time_taken = gpr_time_sub(gpr_now(GPR_CLOCK_REALTIME), start);
  248. fprintf(stderr, " done %lld.%09d s\n",
  249. static_cast<long long>(time_taken.tv_sec),
  250. static_cast<int>(time_taken.tv_nsec));
  251. fflush(stderr);
  252. }
  253. /* Increment m->counter on each iteration; then mark thread as done. */
  254. static void inc(void* v /*=m*/) {
  255. struct test* m = static_cast<struct test*>(v);
  256. int64_t i;
  257. for (i = 0; i != m->iterations; i++) {
  258. gpr_mu_lock(&m->mu);
  259. m->counter++;
  260. gpr_mu_unlock(&m->mu);
  261. }
  262. mark_thread_done(m);
  263. }
  264. /* Increment m->counter under lock acquired with trylock, m->iterations times;
  265. then mark thread as done. */
  266. static void inctry(void* v /*=m*/) {
  267. struct test* m = static_cast<struct test*>(v);
  268. int64_t i;
  269. for (i = 0; i != m->iterations;) {
  270. if (gpr_mu_trylock(&m->mu)) {
  271. m->counter++;
  272. gpr_mu_unlock(&m->mu);
  273. i++;
  274. }
  275. }
  276. mark_thread_done(m);
  277. }
  278. /* Increment counter only when (m->counter%m->threads)==m->thread_id; then mark
  279. thread as done. */
  280. static void inc_by_turns(void* v /*=m*/) {
  281. struct test* m = static_cast<struct test*>(v);
  282. int64_t i;
  283. int id = thread_id(m);
  284. for (i = 0; i != m->iterations; i++) {
  285. gpr_mu_lock(&m->mu);
  286. while ((m->counter % m->threads) != id) {
  287. gpr_cv_wait(&m->cv, &m->mu, gpr_inf_future(GPR_CLOCK_MONOTONIC));
  288. }
  289. m->counter++;
  290. gpr_cv_broadcast(&m->cv);
  291. gpr_mu_unlock(&m->mu);
  292. }
  293. mark_thread_done(m);
  294. }
  295. /* Wait a millisecond and increment counter on each iteration;
  296. then mark thread as done. */
  297. static void inc_with_1ms_delay(void* v /*=m*/) {
  298. struct test* m = static_cast<struct test*>(v);
  299. int64_t i;
  300. for (i = 0; i != m->iterations; i++) {
  301. gpr_timespec deadline;
  302. gpr_mu_lock(&m->mu);
  303. deadline = gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC),
  304. gpr_time_from_micros(1000, GPR_TIMESPAN));
  305. while (!gpr_cv_wait(&m->cv, &m->mu, deadline)) {
  306. }
  307. m->counter++;
  308. gpr_mu_unlock(&m->mu);
  309. }
  310. mark_thread_done(m);
  311. }
  312. /* Wait a millisecond and increment counter on each iteration, using an event
  313. for timing; then mark thread as done. */
  314. static void inc_with_1ms_delay_event(void* v /*=m*/) {
  315. struct test* m = static_cast<struct test*>(v);
  316. int64_t i;
  317. for (i = 0; i != m->iterations; i++) {
  318. gpr_timespec deadline;
  319. deadline = gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
  320. gpr_time_from_micros(1000, GPR_TIMESPAN));
  321. GPR_ASSERT(gpr_event_wait(&m->event, deadline) == nullptr);
  322. gpr_mu_lock(&m->mu);
  323. m->counter++;
  324. gpr_mu_unlock(&m->mu);
  325. }
  326. mark_thread_done(m);
  327. }
  328. /* Produce m->iterations elements on queue m->q, then mark thread as done.
  329. Even threads use queue_append(), and odd threads use queue_try_append()
  330. until it succeeds. */
  331. static void many_producers(void* v /*=m*/) {
  332. struct test* m = static_cast<struct test*>(v);
  333. int64_t i;
  334. int x = thread_id(m);
  335. if ((x & 1) == 0) {
  336. for (i = 0; i != m->iterations; i++) {
  337. queue_append(&m->q, 1);
  338. }
  339. } else {
  340. for (i = 0; i != m->iterations; i++) {
  341. while (!queue_try_append(&m->q, 1)) {
  342. }
  343. }
  344. }
  345. mark_thread_done(m);
  346. }
  347. /* Consume elements from m->q until m->threads*m->iterations are seen,
  348. wait an extra second to confirm that no more elements are arriving,
  349. then mark thread as done. */
  350. static void consumer(void* v /*=m*/) {
  351. struct test* m = static_cast<struct test*>(v);
  352. int64_t n = m->iterations * m->threads;
  353. int64_t i;
  354. int value;
  355. for (i = 0; i != n; i++) {
  356. queue_remove(&m->q, &value, gpr_inf_future(GPR_CLOCK_MONOTONIC));
  357. }
  358. gpr_mu_lock(&m->mu);
  359. m->counter = n;
  360. gpr_mu_unlock(&m->mu);
  361. GPR_ASSERT(
  362. !queue_remove(&m->q, &value,
  363. gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC),
  364. gpr_time_from_micros(1000000, GPR_TIMESPAN))));
  365. mark_thread_done(m);
  366. }
  367. /* Increment m->stats_counter m->iterations times, transfer counter value to
  368. m->counter, then mark thread as done. */
  369. static void statsinc(void* v /*=m*/) {
  370. struct test* m = static_cast<struct test*>(v);
  371. int64_t i;
  372. for (i = 0; i != m->iterations; i++) {
  373. gpr_stats_inc(&m->stats_counter, 1);
  374. }
  375. gpr_mu_lock(&m->mu);
  376. m->counter = gpr_stats_read(&m->stats_counter);
  377. gpr_mu_unlock(&m->mu);
  378. mark_thread_done(m);
  379. }
  380. /* Increment m->refcount by m->incr_step for m->iterations times. Decrement
  381. m->thread_refcount once, and if it reaches zero, set m->event to (void*)1;
  382. then mark thread as done. */
  383. static void refinc(void* v /*=m*/) {
  384. struct test* m = static_cast<struct test*>(v);
  385. int64_t i;
  386. for (i = 0; i != m->iterations; i++) {
  387. if (m->incr_step == 1) {
  388. gpr_ref(&m->refcount);
  389. } else {
  390. gpr_refn(&m->refcount, m->incr_step);
  391. }
  392. }
  393. if (gpr_unref(&m->thread_refcount)) {
  394. gpr_event_set(&m->event, (void*)1);
  395. }
  396. mark_thread_done(m);
  397. }
  398. /* Wait until m->event is set to (void *)1, then decrement m->refcount by 1
  399. (m->threads * m->iterations * m->incr_step) times, and ensure that the last
  400. decrement caused the counter to reach zero, then mark thread as done. */
  401. static void refcheck(void* v /*=m*/) {
  402. struct test* m = static_cast<struct test*>(v);
  403. int64_t n = m->iterations * m->threads * m->incr_step;
  404. int64_t i;
  405. GPR_ASSERT(gpr_event_wait(&m->event, gpr_inf_future(GPR_CLOCK_REALTIME)) ==
  406. (void*)1);
  407. GPR_ASSERT(gpr_event_get(&m->event) == (void*)1);
  408. for (i = 1; i != n; i++) {
  409. GPR_ASSERT(!gpr_unref(&m->refcount));
  410. m->counter++;
  411. }
  412. GPR_ASSERT(gpr_unref(&m->refcount));
  413. m->counter++;
  414. mark_thread_done(m);
  415. }
  416. /* ------------------------------------------------- */
  417. int main(int argc, char* argv[]) {
  418. grpc_test_init(argc, argv);
  419. test("mutex", &inc, nullptr, 1, 1);
  420. test("mutex try", &inctry, nullptr, 1, 1);
  421. test("cv", &inc_by_turns, nullptr, 1, 1);
  422. test("timedcv", &inc_with_1ms_delay, nullptr, 1, 1);
  423. test("queue", &many_producers, &consumer, 10, 1);
  424. test("stats_counter", &statsinc, nullptr, 1, 1);
  425. test("refcount by 1", &refinc, &refcheck, 1, 1);
  426. test("refcount by 3", &refinc, &refcheck, 1, 3); /* incr_step of 3 is an
  427. arbitrary choice. Any
  428. number > 1 is okay here */
  429. test("timedevent", &inc_with_1ms_delay_event, nullptr, 1, 1);
  430. return 0;
  431. }