Brian Silverman | f5f3490 | 2015-03-29 17:57:59 -0400 | [diff] [blame] | 1 | #include "aos/common/event.h" |
| 2 | |
| 3 | #include <thread> |
| 4 | |
| 5 | #include "gtest/gtest.h" |
| 6 | |
| 7 | #include "aos/common/queue_testutils.h" |
| 8 | #include "aos/common/time.h" |
| 9 | |
| 10 | namespace aos { |
| 11 | namespace testing { |
| 12 | |
| 13 | class EventTest : public ::testing::Test { |
| 14 | public: |
| 15 | Event test_event; |
| 16 | |
| 17 | protected: |
| 18 | void SetUp() override { |
| 19 | ::aos::common::testing::EnableTestLogging(); |
| 20 | } |
| 21 | }; |
| 22 | |
| 23 | // Makes sure that basic operations with no blocking or anything work. |
| 24 | TEST_F(EventTest, Basic) { |
| 25 | EXPECT_FALSE(test_event.Clear()); |
| 26 | EXPECT_FALSE(test_event.Clear()); |
| 27 | |
| 28 | test_event.Set(); |
| 29 | test_event.Wait(); |
| 30 | EXPECT_TRUE(test_event.Clear()); |
| 31 | EXPECT_FALSE(test_event.Clear()); |
| 32 | } |
| 33 | |
| 34 | // Tests that tsan understands that events establish a happens-before |
| 35 | // relationship. |
| 36 | TEST_F(EventTest, ThreadSanitizer) { |
Brian Silverman | d6ee9a1 | 2015-03-31 01:37:49 -0400 | [diff] [blame^] | 37 | for (int i = 0; i < 3000; ++i) { |
Brian Silverman | f5f3490 | 2015-03-29 17:57:59 -0400 | [diff] [blame] | 38 | int variable = 0; |
Brian Silverman | d6ee9a1 | 2015-03-31 01:37:49 -0400 | [diff] [blame^] | 39 | test_event.Clear(); |
Brian Silverman | f5f3490 | 2015-03-29 17:57:59 -0400 | [diff] [blame] | 40 | ::std::thread thread([this, &variable]() { |
| 41 | test_event.Wait(); |
| 42 | --variable; |
| 43 | }); |
| 44 | ++variable; |
| 45 | test_event.Set(); |
| 46 | thread.join(); |
| 47 | EXPECT_EQ(0, variable); |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | // Tests that an event blocks correctly. |
| 52 | TEST_F(EventTest, Blocks) { |
| 53 | time::Time start_time, finish_time; |
Brian Silverman | d6ee9a1 | 2015-03-31 01:37:49 -0400 | [diff] [blame^] | 54 | // Without this, it sometimes manages to fail under tsan. |
| 55 | Event started; |
| 56 | ::std::thread thread([this, &start_time, &finish_time, &started]() { |
Brian Silverman | f5f3490 | 2015-03-29 17:57:59 -0400 | [diff] [blame] | 57 | start_time = time::Time::Now(); |
Brian Silverman | d6ee9a1 | 2015-03-31 01:37:49 -0400 | [diff] [blame^] | 58 | started.Set(); |
Brian Silverman | f5f3490 | 2015-03-29 17:57:59 -0400 | [diff] [blame] | 59 | test_event.Wait(); |
| 60 | finish_time = time::Time::Now(); |
| 61 | }); |
| 62 | static const time::Time kWaitTime = time::Time::InSeconds(0.05); |
Brian Silverman | d6ee9a1 | 2015-03-31 01:37:49 -0400 | [diff] [blame^] | 63 | started.Wait(); |
Brian Silverman | f5f3490 | 2015-03-29 17:57:59 -0400 | [diff] [blame] | 64 | time::SleepFor(kWaitTime); |
| 65 | test_event.Set(); |
| 66 | thread.join(); |
| 67 | EXPECT_GE(finish_time - start_time, kWaitTime); |
| 68 | } |
| 69 | |
| 70 | } // namespace testing |
| 71 | } // namespace aos |