sync_test.cc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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 <stdio.h>
  20. #include <stdlib.h>
  21. #include <grpc/support/alloc.h>
  22. #include <grpc/support/log.h>
  23. #include <grpc/support/sync.h>
  24. #include <grpc/support/time.h>
  25. #include "src/core/lib/gprpp/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 nthreads; /* number of threads */
  124. grpc_core::Thread* threads;
  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 nthreads, int64_t iterations, int incr_step) {
  141. struct test* m = static_cast<struct test*>(gpr_malloc(sizeof(*m)));
  142. m->nthreads = nthreads;
  143. m->threads = static_cast<grpc_core::Thread*>(
  144. gpr_malloc(sizeof(*m->threads) * nthreads));
  145. m->iterations = iterations;
  146. m->counter = 0;
  147. m->thread_count = 0;
  148. m->done = nthreads;
  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, nthreads);
  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->threads);
  167. gpr_free(m);
  168. }
  169. /* Create m->nthreads 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->nthreads; i++) {
  173. m->threads[i] = grpc_core::Thread("grpc_create_threads", body, m);
  174. m->threads[i].Start();
  175. }
  176. }
  177. /* Wait until all threads report done. */
  178. static void test_wait(struct test* m) {
  179. gpr_mu_lock(&m->mu);
  180. while (m->done != 0) {
  181. gpr_cv_wait(&m->done_cv, &m->mu, gpr_inf_future(GPR_CLOCK_MONOTONIC));
  182. }
  183. gpr_mu_unlock(&m->mu);
  184. for (int i = 0; i != m->nthreads; i++) {
  185. m->threads[i].Join();
  186. }
  187. }
  188. /* Get an integer thread id in the raneg 0..nthreads-1 */
  189. static int thread_id(struct test* m) {
  190. int id;
  191. gpr_mu_lock(&m->mu);
  192. id = m->thread_count++;
  193. gpr_mu_unlock(&m->mu);
  194. return id;
  195. }
  196. /* Indicate that a thread is done, by decrementing m->done
  197. and signalling done_cv if m->done==0. */
  198. static void mark_thread_done(struct test* m) {
  199. gpr_mu_lock(&m->mu);
  200. GPR_ASSERT(m->done != 0);
  201. m->done--;
  202. if (m->done == 0) {
  203. gpr_cv_signal(&m->done_cv);
  204. }
  205. gpr_mu_unlock(&m->mu);
  206. }
  207. /* Test several threads running (*body)(struct test *m) for increasing settings
  208. of m->iterations, until about timeout_s to 2*timeout_s seconds have elapsed.
  209. If extra!=NULL, run (*extra)(m) in an additional thread.
  210. incr_step controls by how much m->refcount should be incremented/decremented
  211. (if at all) each time in the tests.
  212. */
  213. static void test(const char* name, void (*body)(void* m),
  214. void (*extra)(void* m), int timeout_s, int incr_step) {
  215. int64_t iterations = 8;
  216. struct test* m;
  217. gpr_timespec start = gpr_now(GPR_CLOCK_REALTIME);
  218. gpr_timespec time_taken;
  219. gpr_timespec deadline = gpr_time_add(
  220. start, gpr_time_from_micros(static_cast<int64_t>(timeout_s) * 1000000,
  221. GPR_TIMESPAN));
  222. fprintf(stderr, "%s:", name);
  223. fflush(stderr);
  224. while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0) {
  225. fprintf(stderr, " %ld", static_cast<long>(iterations));
  226. fflush(stderr);
  227. m = test_new(10, iterations, incr_step);
  228. grpc_core::Thread extra_thd;
  229. if (extra != nullptr) {
  230. extra_thd = grpc_core::Thread(name, extra, m);
  231. extra_thd.Start();
  232. m->done++; /* one more thread to wait for */
  233. }
  234. test_create_threads(m, body);
  235. test_wait(m);
  236. if (extra != nullptr) {
  237. extra_thd.Join();
  238. }
  239. if (m->counter != m->nthreads * m->iterations * m->incr_step) {
  240. fprintf(stderr, "counter %ld threads %d iterations %ld\n",
  241. static_cast<long>(m->counter), m->nthreads,
  242. static_cast<long>(m->iterations));
  243. fflush(stderr);
  244. GPR_ASSERT(0);
  245. }
  246. test_destroy(m);
  247. iterations <<= 1;
  248. }
  249. time_taken = gpr_time_sub(gpr_now(GPR_CLOCK_REALTIME), start);
  250. fprintf(stderr, " done %lld.%09d s\n",
  251. static_cast<long long>(time_taken.tv_sec),
  252. static_cast<int>(time_taken.tv_nsec));
  253. fflush(stderr);
  254. }
  255. /* Increment m->counter on each iteration; then mark thread as done. */
  256. static void inc(void* v /*=m*/) {
  257. struct test* m = static_cast<struct test*>(v);
  258. int64_t i;
  259. for (i = 0; i != m->iterations; i++) {
  260. gpr_mu_lock(&m->mu);
  261. m->counter++;
  262. gpr_mu_unlock(&m->mu);
  263. }
  264. mark_thread_done(m);
  265. }
  266. /* Increment m->counter under lock acquired with trylock, m->iterations times;
  267. then mark thread as done. */
  268. static void inctry(void* v /*=m*/) {
  269. struct test* m = static_cast<struct test*>(v);
  270. int64_t i;
  271. for (i = 0; i != m->iterations;) {
  272. if (gpr_mu_trylock(&m->mu)) {
  273. m->counter++;
  274. gpr_mu_unlock(&m->mu);
  275. i++;
  276. }
  277. }
  278. mark_thread_done(m);
  279. }
  280. /* Increment counter only when (m->counter%m->nthreads)==m->thread_id; then mark
  281. thread as done. */
  282. static void inc_by_turns(void* v /*=m*/) {
  283. struct test* m = static_cast<struct test*>(v);
  284. int64_t i;
  285. int id = thread_id(m);
  286. for (i = 0; i != m->iterations; i++) {
  287. gpr_mu_lock(&m->mu);
  288. while ((m->counter % m->nthreads) != id) {
  289. gpr_cv_wait(&m->cv, &m->mu, gpr_inf_future(GPR_CLOCK_MONOTONIC));
  290. }
  291. m->counter++;
  292. gpr_cv_broadcast(&m->cv);
  293. gpr_mu_unlock(&m->mu);
  294. }
  295. mark_thread_done(m);
  296. }
  297. /* Wait a millisecond and increment counter on each iteration;
  298. then mark thread as done. */
  299. static void inc_with_1ms_delay(void* v /*=m*/) {
  300. struct test* m = static_cast<struct test*>(v);
  301. int64_t i;
  302. for (i = 0; i != m->iterations; i++) {
  303. gpr_timespec deadline;
  304. gpr_mu_lock(&m->mu);
  305. deadline = gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC),
  306. gpr_time_from_micros(1000, GPR_TIMESPAN));
  307. while (!gpr_cv_wait(&m->cv, &m->mu, deadline)) {
  308. }
  309. m->counter++;
  310. gpr_mu_unlock(&m->mu);
  311. }
  312. mark_thread_done(m);
  313. }
  314. /* Wait a millisecond and increment counter on each iteration, using an event
  315. for timing; then mark thread as done. */
  316. static void inc_with_1ms_delay_event(void* v /*=m*/) {
  317. struct test* m = static_cast<struct test*>(v);
  318. int64_t i;
  319. for (i = 0; i != m->iterations; i++) {
  320. gpr_timespec deadline;
  321. deadline = gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
  322. gpr_time_from_micros(1000, GPR_TIMESPAN));
  323. GPR_ASSERT(gpr_event_wait(&m->event, deadline) == nullptr);
  324. gpr_mu_lock(&m->mu);
  325. m->counter++;
  326. gpr_mu_unlock(&m->mu);
  327. }
  328. mark_thread_done(m);
  329. }
  330. /* Produce m->iterations elements on queue m->q, then mark thread as done.
  331. Even threads use queue_append(), and odd threads use queue_try_append()
  332. until it succeeds. */
  333. static void many_producers(void* v /*=m*/) {
  334. struct test* m = static_cast<struct test*>(v);
  335. int64_t i;
  336. int x = thread_id(m);
  337. if ((x & 1) == 0) {
  338. for (i = 0; i != m->iterations; i++) {
  339. queue_append(&m->q, 1);
  340. }
  341. } else {
  342. for (i = 0; i != m->iterations; i++) {
  343. while (!queue_try_append(&m->q, 1)) {
  344. }
  345. }
  346. }
  347. mark_thread_done(m);
  348. }
  349. /* Consume elements from m->q until m->nthreads*m->iterations are seen,
  350. wait an extra second to confirm that no more elements are arriving,
  351. then mark thread as done. */
  352. static void consumer(void* v /*=m*/) {
  353. struct test* m = static_cast<struct test*>(v);
  354. int64_t n = m->iterations * m->nthreads;
  355. int64_t i;
  356. int value;
  357. for (i = 0; i != n; i++) {
  358. queue_remove(&m->q, &value, gpr_inf_future(GPR_CLOCK_MONOTONIC));
  359. }
  360. gpr_mu_lock(&m->mu);
  361. m->counter = n;
  362. gpr_mu_unlock(&m->mu);
  363. GPR_ASSERT(
  364. !queue_remove(&m->q, &value,
  365. gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC),
  366. gpr_time_from_micros(1000000, GPR_TIMESPAN))));
  367. mark_thread_done(m);
  368. }
  369. /* Increment m->stats_counter m->iterations times, transfer counter value to
  370. m->counter, then mark thread as done. */
  371. static void statsinc(void* v /*=m*/) {
  372. struct test* m = static_cast<struct test*>(v);
  373. int64_t i;
  374. for (i = 0; i != m->iterations; i++) {
  375. gpr_stats_inc(&m->stats_counter, 1);
  376. }
  377. gpr_mu_lock(&m->mu);
  378. m->counter = gpr_stats_read(&m->stats_counter);
  379. gpr_mu_unlock(&m->mu);
  380. mark_thread_done(m);
  381. }
  382. /* Increment m->refcount by m->incr_step for m->iterations times. Decrement
  383. m->thread_refcount once, and if it reaches zero, set m->event to (void*)1;
  384. then mark thread as done. */
  385. static void refinc(void* v /*=m*/) {
  386. struct test* m = static_cast<struct test*>(v);
  387. int64_t i;
  388. for (i = 0; i != m->iterations; i++) {
  389. if (m->incr_step == 1) {
  390. gpr_ref(&m->refcount);
  391. } else {
  392. gpr_refn(&m->refcount, m->incr_step);
  393. }
  394. }
  395. if (gpr_unref(&m->thread_refcount)) {
  396. gpr_event_set(&m->event, reinterpret_cast<void*>(1));
  397. }
  398. mark_thread_done(m);
  399. }
  400. /* Wait until m->event is set to (void *)1, then decrement m->refcount by 1
  401. (m->nthreads * m->iterations * m->incr_step) times, and ensure that the last
  402. decrement caused the counter to reach zero, then mark thread as done. */
  403. static void refcheck(void* v /*=m*/) {
  404. struct test* m = static_cast<struct test*>(v);
  405. int64_t n = m->iterations * m->nthreads * m->incr_step;
  406. int64_t i;
  407. GPR_ASSERT(gpr_event_wait(&m->event, gpr_inf_future(GPR_CLOCK_REALTIME)) ==
  408. (void*)1);
  409. GPR_ASSERT(gpr_event_get(&m->event) == (void*)1);
  410. for (i = 1; i != n; i++) {
  411. GPR_ASSERT(!gpr_unref(&m->refcount));
  412. m->counter++;
  413. }
  414. GPR_ASSERT(gpr_unref(&m->refcount));
  415. m->counter++;
  416. mark_thread_done(m);
  417. }
  418. /* ------------------------------------------------- */
  419. int main(int argc, char* argv[]) {
  420. grpc::testing::TestEnvironment env(argc, argv);
  421. test("mutex", &inc, nullptr, 1, 1);
  422. test("mutex try", &inctry, nullptr, 1, 1);
  423. test("cv", &inc_by_turns, nullptr, 1, 1);
  424. test("timedcv", &inc_with_1ms_delay, nullptr, 1, 1);
  425. test("queue", &many_producers, &consumer, 10, 1);
  426. test("stats_counter", &statsinc, nullptr, 1, 1);
  427. test("refcount by 1", &refinc, &refcheck, 1, 1);
  428. test("refcount by 3", &refinc, &refcheck, 1, 3); /* incr_step of 3 is an
  429. arbitrary choice. Any
  430. number > 1 is okay here */
  431. test("timedevent", &inc_with_1ms_delay_event, nullptr, 1, 1);
  432. return 0;
  433. }