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) { |
| 37 | for (int i = 0; i < 1000; ++i) { |
| 38 | int variable = 0; |
| 39 | ::std::thread thread([this, &variable]() { |
| 40 | test_event.Wait(); |
| 41 | --variable; |
| 42 | }); |
| 43 | ++variable; |
| 44 | test_event.Set(); |
| 45 | thread.join(); |
| 46 | EXPECT_EQ(0, variable); |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | // Tests that an event blocks correctly. |
| 51 | TEST_F(EventTest, Blocks) { |
| 52 | time::Time start_time, finish_time; |
| 53 | ::std::thread thread([this, &start_time, &finish_time]() { |
| 54 | start_time = time::Time::Now(); |
| 55 | test_event.Wait(); |
| 56 | finish_time = time::Time::Now(); |
| 57 | }); |
| 58 | static const time::Time kWaitTime = time::Time::InSeconds(0.05); |
| 59 | time::SleepFor(kWaitTime); |
| 60 | test_event.Set(); |
| 61 | thread.join(); |
| 62 | EXPECT_GE(finish_time - start_time, kWaitTime); |
| 63 | } |
| 64 | |
| 65 | } // namespace testing |
| 66 | } // namespace aos |