blob: d8671eb2cf17e19ed444e127e29fbe1a3c431cc3 [file] [log] [blame]
Brian Silvermanf5f34902015-03-29 17:57:59 -04001#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
10namespace aos {
11namespace testing {
12
13class 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.
24TEST_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.
36TEST_F(EventTest, ThreadSanitizer) {
Brian Silvermand6ee9a12015-03-31 01:37:49 -040037 for (int i = 0; i < 3000; ++i) {
Brian Silvermanf5f34902015-03-29 17:57:59 -040038 int variable = 0;
Brian Silvermand6ee9a12015-03-31 01:37:49 -040039 test_event.Clear();
Brian Silvermanf5f34902015-03-29 17:57:59 -040040 ::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.
52TEST_F(EventTest, Blocks) {
53 time::Time start_time, finish_time;
Brian Silvermand6ee9a12015-03-31 01:37:49 -040054 // Without this, it sometimes manages to fail under tsan.
55 Event started;
56 ::std::thread thread([this, &start_time, &finish_time, &started]() {
Brian Silvermanf5f34902015-03-29 17:57:59 -040057 start_time = time::Time::Now();
Brian Silvermand6ee9a12015-03-31 01:37:49 -040058 started.Set();
Brian Silvermanf5f34902015-03-29 17:57:59 -040059 test_event.Wait();
60 finish_time = time::Time::Now();
61 });
62 static const time::Time kWaitTime = time::Time::InSeconds(0.05);
Brian Silvermand6ee9a12015-03-31 01:37:49 -040063 started.Wait();
Brian Silvermanf5f34902015-03-29 17:57:59 -040064 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