2 * Copyright 2018-present Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include <folly/synchronization/Tearable.h>
22 #include <folly/portability/GTest.h>
24 using namespace folly;
29 Data(unsigned char value) {
33 void setValue(unsigned char value) {
34 for (auto& item : contents) {
39 void checkValue(unsigned char value) {
40 for (auto& item : contents) {
41 ASSERT_EQ(value, item);
45 void checkValue2(unsigned char value1, unsigned char value2) {
46 for (auto& item : contents) {
47 ASSERT_TRUE(item == value1 || item == value2);
51 // Note the odd size -- this will hopefully expose layout bugs under
53 unsigned char contents[99];
56 TEST(TearableTest, BasicOperations) {
57 Tearable<Data> tearable;
60 for (char c = 0; c < 10; ++c) {
68 TEST(TearableTest, Races) {
69 std::atomic<bool> stop(false);
70 Tearable<Data> tearable(Data(1));
71 std::thread write1([&]() {
73 while (!stop.load(std::memory_order_relaxed)) {
74 tearable.store(data0);
77 std::thread write2([&]() {
79 while (!stop.load(std::memory_order_relaxed)) {
80 tearable.store(data1);
84 for (int i = 0; i < 100 * 1000; ++i) {
86 val.checkValue2(1, 2);
88 stop.store(true, std::memory_order_relaxed);