AtomicStructTest.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. * Copyright 2013-present Facebook, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include <folly/synchronization/AtomicStruct.h>
  17. #include <folly/portability/GTest.h>
  18. using namespace folly;
  19. struct TwoBy32 {
  20. uint32_t left;
  21. uint32_t right;
  22. };
  23. TEST(AtomicStruct, two_by_32) {
  24. AtomicStruct<TwoBy32> a(TwoBy32{10, 20});
  25. TwoBy32 av = a;
  26. EXPECT_EQ(av.left, 10);
  27. EXPECT_EQ(av.right, 20);
  28. EXPECT_TRUE(a.compare_exchange_strong(av, TwoBy32{30, 40}));
  29. EXPECT_FALSE(a.compare_exchange_weak(av, TwoBy32{31, 41}));
  30. EXPECT_EQ(av.left, 30);
  31. EXPECT_TRUE(a.is_lock_free());
  32. auto b = a.exchange(TwoBy32{50, 60});
  33. EXPECT_EQ(b.left, 30);
  34. EXPECT_EQ(b.right, 40);
  35. EXPECT_EQ(a.load().left, 50);
  36. a = TwoBy32{70, 80};
  37. EXPECT_EQ(a.load().right, 80);
  38. a.store(TwoBy32{90, 100});
  39. av = a;
  40. EXPECT_EQ(av.left, 90);
  41. AtomicStruct<TwoBy32> c;
  42. c = b;
  43. EXPECT_EQ(c.load().right, 40);
  44. }
  45. template <size_t I>
  46. struct S {
  47. char x[I];
  48. };
  49. TEST(AtomicStruct, size_selection) {
  50. EXPECT_EQ(sizeof(AtomicStruct<S<1>>), 1);
  51. EXPECT_EQ(sizeof(AtomicStruct<S<2>>), 2);
  52. EXPECT_EQ(sizeof(AtomicStruct<S<3>>), 4);
  53. EXPECT_EQ(sizeof(AtomicStruct<S<4>>), 4);
  54. EXPECT_EQ(sizeof(AtomicStruct<S<5>>), 8);
  55. EXPECT_EQ(sizeof(AtomicStruct<S<6>>), 8);
  56. EXPECT_EQ(sizeof(AtomicStruct<S<7>>), 8);
  57. EXPECT_EQ(sizeof(AtomicStruct<S<8>>), 8);
  58. }