Imported Upstream version 1.41.0
[platform/upstream/grpc.git] / test / core / gpr / tls_test.cc
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 local storage support. */
20
21 #include "src/core/lib/gpr/tls.h"
22
23 #include <array>
24
25 #include <gtest/gtest.h>
26
27 #include "src/core/lib/gprpp/thd.h"
28 #include "test/core/util/test_config.h"
29
30 struct BiggerThanMachineWord {
31   size_t a, b;
32   uint8_t c;
33 };
34
35 static GPR_THREAD_LOCAL(BiggerThanMachineWord) test_var;
36 // Fails to compile: static GPR_THREAD_LOCAL(std::unique_ptr<char>) non_trivial;
37
38 namespace {
39 void thd_body(void*) {
40   for (size_t i = 0; i < 100000; i++) {
41     BiggerThanMachineWord next = {i, i, uint8_t(i)};
42     test_var = next;
43     BiggerThanMachineWord read = test_var;
44     ASSERT_EQ(read.a, i);
45     ASSERT_EQ(read.b, i);
46     ASSERT_EQ(read.c, uint8_t(i)) << i;
47   }
48 }
49
50 TEST(ThreadLocal, ReadWrite) {
51   std::array<grpc_core::Thread, 100> threads;
52   for (grpc_core::Thread& th : threads) {
53     th = grpc_core::Thread("grpc_tls_test", thd_body, nullptr);
54     th.Start();
55   }
56   for (grpc_core::Thread& th : threads) {
57     th.Join();
58   }
59 }
60
61 }  // namespace
62
63 int main(int argc, char* argv[]) {
64   grpc::testing::TestEnvironment env(argc, argv);
65   ::testing::InitGoogleTest(&argc, argv);
66   return RUN_ALL_TESTS();
67 }