tls_test.cc 1.7 KB

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