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 thread support. */
20
21 #include "src/core/lib/gprpp/thd.h"
22
23 #include <stdio.h>
24 #include <stdlib.h>
25
26 #include <grpc/support/log.h>
27 #include <grpc/support/sync.h>
28 #include <grpc/support/time.h>
29
30 #include "test/core/util/test_config.h"
31
32 #define NUM_THREADS 100
33
34 struct test {
35 gpr_mu mu;
36 int n;
37 int is_done;
38 gpr_cv done_cv;
39 };
40
41 /* A Thread body. Decrement t->n, and if is becomes zero, set t->done. */
thd_body1(void * v)42 static void thd_body1(void* v) {
43 struct test* t = static_cast<struct test*>(v);
44 gpr_mu_lock(&t->mu);
45 t->n--;
46 if (t->n == 0) {
47 t->is_done = 1;
48 gpr_cv_signal(&t->done_cv);
49 }
50 gpr_mu_unlock(&t->mu);
51 }
52
53 /* Test that we can create a number of threads, wait for them, and join them. */
test1(void)54 static void test1(void) {
55 grpc_core::Thread thds[NUM_THREADS];
56 struct test t;
57 gpr_mu_init(&t.mu);
58 gpr_cv_init(&t.done_cv);
59 t.n = NUM_THREADS;
60 t.is_done = 0;
61 for (auto& th : thds) {
62 th = grpc_core::Thread("grpc_thread_body1_test", &thd_body1, &t);
63 th.Start();
64 }
65 gpr_mu_lock(&t.mu);
66 while (!t.is_done) {
67 gpr_cv_wait(&t.done_cv, &t.mu, gpr_inf_future(GPR_CLOCK_REALTIME));
68 }
69 gpr_mu_unlock(&t.mu);
70 for (auto& th : thds) {
71 th.Join();
72 }
73 GPR_ASSERT(t.n == 0);
74 gpr_mu_destroy(&t.mu);
75 gpr_cv_destroy(&t.done_cv);
76 }
77
thd_body2(void *)78 static void thd_body2(void* /*v*/) {}
79
80 /* Test that we can create a number of threads and join them. */
test2(void)81 static void test2(void) {
82 grpc_core::Thread thds[NUM_THREADS];
83 for (auto& th : thds) {
84 bool ok;
85 th = grpc_core::Thread("grpc_thread_body2_test", &thd_body2, nullptr, &ok);
86 GPR_ASSERT(ok);
87 th.Start();
88 }
89 for (auto& th : thds) {
90 th.Join();
91 }
92 }
93
94 /* ------------------------------------------------- */
95
main(int argc,char * argv[])96 int main(int argc, char* argv[]) {
97 grpc::testing::TestEnvironment env(argc, argv);
98 test1();
99 test2();
100 return 0;
101 }
102