Debian Codegraph @

test/core/gpr/sync_test.cc

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