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