1 | #include <c10/util/Synchronized.h> |
---|---|
2 | #include <gtest/gtest.h> |
3 | |
4 | #include <array> |
5 | #include <thread> |
6 | |
7 | namespace { |
8 | |
9 | TEST(Synchronized, TestSingleThreadExecution) { |
10 | c10::Synchronized<int> iv(0); |
11 | const int kMaxValue = 100; |
12 | for (int i = 0; i < kMaxValue; ++i) { |
13 | auto ret = iv.withLock([](int& iv) { return ++iv; }); |
14 | EXPECT_EQ(ret, i + 1); |
15 | } |
16 | |
17 | iv.withLock([kMaxValue](int& iv) { EXPECT_EQ(iv, kMaxValue); }); |
18 | } |
19 | |
20 | TEST(Synchronized, TestMultiThreadedExecution) { |
21 | c10::Synchronized<int> iv(0); |
22 | #define NUM_LOOP_INCREMENTS 10000 |
23 | |
24 | auto thread_cb = [&iv]() { |
25 | for (int i = 0; i < NUM_LOOP_INCREMENTS; ++i) { |
26 | iv.withLock([](int& iv) { ++iv; }); |
27 | } |
28 | }; |
29 | |
30 | std::array<std::thread, 10> threads; |
31 | for (auto& t : threads) { |
32 | t = std::thread(thread_cb); |
33 | } |
34 | |
35 | for (auto& t : threads) { |
36 | t.join(); |
37 | } |
38 | |
39 | iv.withLock([](int& iv) { EXPECT_EQ(iv, NUM_LOOP_INCREMENTS * 10); }); |
40 | #undef NUM_LOOP_INCREMENTS |
41 | } |
42 | |
43 | } // namespace |
44 |