diff --git a/engine/src/flutter/fml/BUILD.gn b/engine/src/flutter/fml/BUILD.gn index e00cd085ae..0e561b87cb 100644 --- a/engine/src/flutter/fml/BUILD.gn +++ b/engine/src/flutter/fml/BUILD.gn @@ -5,6 +5,7 @@ source_set("fml") { sources = [ "build_config.h", + "closure.h", "compiler_specific.h", "eintr_wrapper.h", "export.h", @@ -34,6 +35,10 @@ source_set("fml") { "native_library.h", "paths.cc", "paths.h", + "synchronization/thread_annotations.h", + "synchronization/thread_checker.h", + "synchronization/waitable_event.cc", + "synchronization/waitable_event.h", "task_runner.cc", "task_runner.h", "thread.cc", @@ -149,6 +154,9 @@ executable("fml_unittests") { "memory/ref_counted_unittest.cc", "memory/weak_ptr_unittest.cc", "message_loop_unittests.cc", + "synchronization/thread_annotations_unittest.cc", + "synchronization/thread_checker_unittest.cc", + "synchronization/waitable_event_unittest.cc", "thread_local_unittests.cc", "thread_unittests.cc", "time/time_delta_unittest.cc", diff --git a/engine/src/flutter/fml/closure.h b/engine/src/flutter/fml/closure.h new file mode 100644 index 0000000000..f40c0b2d0c --- /dev/null +++ b/engine/src/flutter/fml/closure.h @@ -0,0 +1,16 @@ +// Copyright 2016 The Fuchsia Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef FLUTTER_FML_CLOSURE_H_ +#define FLUTTER_FML_CLOSURE_H_ + +#include + +namespace fml { + +using closure = std::function; + +} // namespace fml + +#endif // FLUTTER_FML_CLOSURE_H_ diff --git a/engine/src/flutter/fml/synchronization/thread_annotations.h b/engine/src/flutter/fml/synchronization/thread_annotations.h new file mode 100644 index 0000000000..4123804e57 --- /dev/null +++ b/engine/src/flutter/fml/synchronization/thread_annotations.h @@ -0,0 +1,89 @@ +// Copyright 2016 The Fuchsia Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Macros for static thread-safety analysis. +// +// These are from http://clang.llvm.org/docs/ThreadSafetyAnalysis.html (and thus +// really derive from google3's thread_annotations.h). +// +// TODO(vtl): We're still using the old-fashioned, deprecated annotations +// ("locks" instead of "capabilities"), since the new ones don't work yet (in +// particular, |TRY_ACQUIRE()| doesn't work: b/19264527). +// https://github.com/domokit/mojo/issues/314 + +#ifndef FLUTTER_FML_SYNCHRONIZATION_THREAD_ANNOTATIONS_H_ +#define FLUTTER_FML_SYNCHRONIZATION_THREAD_ANNOTATIONS_H_ + +// Enable thread-safety attributes only with clang. +// The attributes can be safely erased when compiling with other compilers. +#if defined(__clang__) +#define FML_THREAD_ANNOTATION_ATTRIBUTE__(x) __attribute__((x)) +#else +#define FML_THREAD_ANNOTATION_ATTRIBUTE__(x) +#endif + +#define FML_GUARDED_BY(x) FML_THREAD_ANNOTATION_ATTRIBUTE__(guarded_by(x)) + +#define FML_PT_GUARDED_BY(x) FML_THREAD_ANNOTATION_ATTRIBUTE__(pt_guarded_by(x)) + +#define FML_ACQUIRE(...) \ + FML_THREAD_ANNOTATION_ATTRIBUTE__(acquire_capability(__VA_ARGS__)) + +#define FML_RELEASE(...) \ + FML_THREAD_ANNOTATION_ATTRIBUTE__(release_capability(__VA_ARGS__)) + +#define FML_ACQUIRED_AFTER(...) \ + FML_THREAD_ANNOTATION_ATTRIBUTE__(acquired_after(__VA_ARGS__)) + +#define FML_ACQUIRED_BEFORE(...) \ + FML_THREAD_ANNOTATION_ATTRIBUTE__(acquired_before(__VA_ARGS__)) + +#define FML_EXCLUSIVE_LOCKS_REQUIRED(...) \ + FML_THREAD_ANNOTATION_ATTRIBUTE__(exclusive_locks_required(__VA_ARGS__)) + +#define FML_SHARED_LOCKS_REQUIRED(...) \ + FML_THREAD_ANNOTATION_ATTRIBUTE__(shared_locks_required(__VA_ARGS__)) + +#define FML_LOCKS_EXCLUDED(...) \ + FML_THREAD_ANNOTATION_ATTRIBUTE__(locks_excluded(__VA_ARGS__)) + +#define FML_LOCK_RETURNED(x) FML_THREAD_ANNOTATION_ATTRIBUTE__(lock_returned(x)) + +#define FML_LOCKABLE FML_THREAD_ANNOTATION_ATTRIBUTE__(lockable) + +#define FML_SCOPED_LOCKABLE FML_THREAD_ANNOTATION_ATTRIBUTE__(scoped_lockable) + +#define FML_EXCLUSIVE_LOCK_FUNCTION(...) \ + FML_THREAD_ANNOTATION_ATTRIBUTE__(exclusive_lock_function(__VA_ARGS__)) + +#define FML_SHARED_LOCK_FUNCTION(...) \ + FML_THREAD_ANNOTATION_ATTRIBUTE__(shared_lock_function(__VA_ARGS__)) + +#define FML_ASSERT_EXCLUSIVE_LOCK(...) \ + FML_THREAD_ANNOTATION_ATTRIBUTE__(assert_exclusive_lock(__VA_ARGS__)) + +#define FML_ASSERT_SHARED_LOCK(...) \ + FML_THREAD_ANNOTATION_ATTRIBUTE__(assert_shared_lock(__VA_ARGS__)) + +#define FML_EXCLUSIVE_TRYLOCK_FUNCTION(...) \ + FML_THREAD_ANNOTATION_ATTRIBUTE__(exclusive_trylock_function(__VA_ARGS__)) + +#define FML_SHARED_TRYLOCK_FUNCTION(...) \ + FML_THREAD_ANNOTATION_ATTRIBUTE__(shared_trylock_function(__VA_ARGS__)) + +#define FML_UNLOCK_FUNCTION(...) \ + FML_THREAD_ANNOTATION_ATTRIBUTE__(unlock_function(__VA_ARGS__)) + +#define FML_NO_THREAD_SAFETY_ANALYSIS \ + FML_THREAD_ANNOTATION_ATTRIBUTE__(no_thread_safety_analysis) + +// Use this in the header to annotate a function/method as not being +// thread-safe. This is equivalent to |FML_NO_THREAD_SAFETY_ANALYSIS|, but +// semantically different: it declares that the caller must abide by additional +// restrictions. Limitation: Unfortunately, you can't apply this to a method in +// an interface (i.e., pure virtual method) and have it applied automatically to +// implementations. +#define FML_NOT_THREAD_SAFE FML_NO_THREAD_SAFETY_ANALYSIS + +#endif // FLUTTER_FML_SYNCHRONIZATION_THREAD_ANNOTATIONS_H_ diff --git a/engine/src/flutter/fml/synchronization/thread_annotations_unittest.cc b/engine/src/flutter/fml/synchronization/thread_annotations_unittest.cc new file mode 100644 index 0000000000..12769451dc --- /dev/null +++ b/engine/src/flutter/fml/synchronization/thread_annotations_unittest.cc @@ -0,0 +1,127 @@ +// Copyright 2016 The Fuchsia Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Tests of the static thread annotation macros. These fall into two categories, +// positive tests (testing that correct code compiles and works) and negative +// tests (testing that incorrect code does not compile). +// +// Unfortunately, we don't have systematic/automated negative compilation tests. +// So instead we have some cheesy macros that you can define to enable +// individual compilation failures. + +#include "flutter/fml/synchronization/thread_annotations.h" + +#include + +#include "flutter/fml/macros.h" +#include "gtest/gtest.h" + +// Uncomment these to enable particular compilation failure tests. +// #define NC_GUARDED_BY +// TODO(vtl): |ACQUIRED_{BEFORE,AFTER}()| are currently unimplemented in clang +// as of 2015-07-06 ("To be fixed in a future update."). So this actually +// compiles! +// #define NC_ACQUIRED_BEFORE + +namespace fml { +namespace { + +// Test FML_GUARDED_BY --------------------------------------------------------- + +class GuardedByClass { + public: + GuardedByClass() : x_() {} + ~GuardedByClass() {} + + void GoodSet(int x) { + mu_.lock(); + x_ = x; + mu_.unlock(); + } + +#ifdef NC_GUARDED_BY + void BadSet(int x) { x_ = x; } +#endif + + private: + std::mutex mu_; + int x_ FML_GUARDED_BY(mu_); + + FML_DISALLOW_COPY_AND_ASSIGN(GuardedByClass); +}; + +TEST(ThreadAnnotationsTest, GuardedBy) { + GuardedByClass c; + c.GoodSet(123); +} + +// Test FML_ACQUIRED_BEFORE ---------------------------------------------------- + +class AcquiredBeforeClass2; + +class AcquiredBeforeClass1 { + public: + AcquiredBeforeClass1() {} + ~AcquiredBeforeClass1() {} + + void NoOp() { + mu_.lock(); + mu_.unlock(); + } + +#ifdef NC_ACQUIRED_BEFORE + void BadMethod(AcquiredBeforeClass2* c2); +#endif + + private: + friend class AcquiredBeforeClass2; + + std::mutex mu_; + + FML_DISALLOW_COPY_AND_ASSIGN(AcquiredBeforeClass1); +}; + +class AcquiredBeforeClass2 { + public: + AcquiredBeforeClass2() {} + ~AcquiredBeforeClass2() {} + + void NoOp() { + mu_.lock(); + mu_.unlock(); + } + + void GoodMethod(AcquiredBeforeClass1* c1) { + mu_.lock(); + c1->NoOp(); + mu_.unlock(); + } + + private: + std::mutex mu_ FML_ACQUIRED_BEFORE(AcquiredBeforeClass1::mu_); + + FML_DISALLOW_COPY_AND_ASSIGN(AcquiredBeforeClass2); +}; + +#ifdef NC_ACQUIRED_BEFORE +void AcquiredBeforeClass1::BadMethod(AcquiredBeforeClass2* c2) { + mu_.lock(); + c2->NoOp(); + mu_.unlock(); +} +#endif + +TEST(ThreadAnnotationsTest, AcquiredBefore) { + AcquiredBeforeClass1 c1; + AcquiredBeforeClass2 c2; + c2.GoodMethod(&c1); +#ifdef NC_ACQUIRED_BEFORE + c1.BadMethod(&c2); +#endif +} + +// TODO(vtl): Test more things. + +} // namespace +} // namespace fml diff --git a/engine/src/flutter/fml/synchronization/thread_checker.h b/engine/src/flutter/fml/synchronization/thread_checker.h new file mode 100644 index 0000000000..13a3e6824d --- /dev/null +++ b/engine/src/flutter/fml/synchronization/thread_checker.h @@ -0,0 +1,71 @@ +// Copyright 2016 The Fuchsia Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// A class for checking that the current thread is/isn't the same as an initial +// thread. + +#ifndef FLUTTER_FML_SYNCHRONIZATION_THREAD_CHECKER_H_ +#define FLUTTER_FML_SYNCHRONIZATION_THREAD_CHECKER_H_ + +#include "flutter/fml/build_config.h" + +#if defined(OS_WIN) +#include +#else +#include +#endif + +#include "flutter/fml/logging.h" +#include "flutter/fml/macros.h" + +namespace fml { + +// A simple class that records the identity of the thread that it was created +// on, and at later points can tell if the current thread is the same as its +// creation thread. This class is thread-safe. +// +// Note: Unlike Chromium's |base::ThreadChecker|, this is *not* Debug-only (so +// #ifdef it out if you want something Debug-only). (Rationale: Having a +// |CalledOnValidThread()| that lies in Release builds seems bad. Moreover, +// there's a small space cost to having even an empty class. ) +class ThreadChecker final { + public: +#if defined(OS_WIN) + ThreadChecker() : self_(GetCurrentThreadId()) {} + ~ThreadChecker() {} + + bool IsCreationThreadCurrent() const { return GetCurrentThreadId() == self_; } + + private: + const DWORD self_; + +#else + ThreadChecker() : self_(pthread_self()) {} + ~ThreadChecker() {} + + // Returns true if the current thread is the thread this object was created + // on and false otherwise. + bool IsCreationThreadCurrent() const { + return !!pthread_equal(pthread_self(), self_); + } + + private: + const pthread_t self_; +#endif + + FML_DISALLOW_COPY_AND_ASSIGN(ThreadChecker); +}; + +#ifndef NDEBUG +#define FML_DECLARE_THREAD_CHECKER(c) fml::ThreadChecker c +#define FML_DCHECK_CREATION_THREAD_IS_CURRENT(c) \ + FML_DCHECK((c).IsCreationThreadCurrent()) +#else +#define FML_DECLARE_THREAD_CHECKER(c) +#define FML_DCHECK_CREATION_THREAD_IS_CURRENT(c) ((void)0) +#endif + +} // namespace fml + +#endif // FLUTTER_FML_SYNCHRONIZATION_THREAD_CHECKER_H_ diff --git a/engine/src/flutter/fml/synchronization/thread_checker_unittest.cc b/engine/src/flutter/fml/synchronization/thread_checker_unittest.cc new file mode 100644 index 0000000000..46203e43ad --- /dev/null +++ b/engine/src/flutter/fml/synchronization/thread_checker_unittest.cc @@ -0,0 +1,37 @@ +// Copyright 2016 The Fuchsia Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/fml/synchronization/thread_checker.h" + +#include + +#include "gtest/gtest.h" + +namespace fml { +namespace { + +TEST(ThreadCheckerTest, SameThread) { + ThreadChecker checker; + EXPECT_TRUE(checker.IsCreationThreadCurrent()); +} + +// Note: This test depends on |std::thread| being compatible with +// |pthread_self()|. +TEST(ThreadCheckerTest, DifferentThreads) { + ThreadChecker checker1; + EXPECT_TRUE(checker1.IsCreationThreadCurrent()); + + std::thread thread([&checker1]() { + ThreadChecker checker2; + EXPECT_TRUE(checker2.IsCreationThreadCurrent()); + EXPECT_FALSE(checker1.IsCreationThreadCurrent()); + }); + thread.join(); + + // Note: Without synchronization, we can't look at |checker2| from the main + // thread. +} + +} // namespace +} // namespace fml diff --git a/engine/src/flutter/fml/synchronization/waitable_event.cc b/engine/src/flutter/fml/synchronization/waitable_event.cc new file mode 100644 index 0000000000..04052c60ed --- /dev/null +++ b/engine/src/flutter/fml/synchronization/waitable_event.cc @@ -0,0 +1,167 @@ +// Copyright 2016 The Fuchsia Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/fml/synchronization/waitable_event.h" + +#include "flutter/fml/logging.h" +#include "flutter/fml/time/time_delta.h" +#include "flutter/fml/time/time_point.h" + +#include +#include + +namespace fml { + +// Waits with a timeout on |condition()|. Returns true on timeout, or false if +// |condition()| ever returns true. |condition()| should have no side effects +// (and will always be called with |*mutex| held). +template +bool WaitWithTimeoutImpl(std::unique_lock* locker, + std::condition_variable* cv, + ConditionFn condition, + TimeDelta timeout) { + FML_DCHECK(locker->owns_lock()); + + if (condition()) + return false; + + // We may get spurious wakeups. + TimeDelta wait_remaining = timeout; + TimePoint start = TimePoint::Now(); + while (true) { + if (std::cv_status::timeout == + cv->wait_for(*locker, + std::chrono::nanoseconds(wait_remaining.ToNanoseconds()))) + return true; // Definitely timed out. + + // We may have been awoken. + if (condition()) + return false; + + // Or the wakeup may have been spurious. + TimePoint now = TimePoint::Now(); + FML_DCHECK(now >= start); + TimeDelta elapsed = now - start; + // It's possible that we may have timed out anyway. + if (elapsed >= timeout) + return true; + + // Otherwise, recalculate the amount that we have left to wait. + wait_remaining = timeout - elapsed; + } +} + +// AutoResetWaitableEvent ------------------------------------------------------ + +void AutoResetWaitableEvent::Signal() { + std::lock_guard locker(mutex_); + signaled_ = true; + cv_.notify_one(); +} + +void AutoResetWaitableEvent::Reset() { + std::lock_guard locker(mutex_); + signaled_ = false; +} + +void AutoResetWaitableEvent::Wait() { + std::unique_lock locker(mutex_); + while (!signaled_) + cv_.wait(locker); + signaled_ = false; +} + +bool AutoResetWaitableEvent::WaitWithTimeout(TimeDelta timeout) { + std::unique_lock locker(mutex_); + + if (signaled_) { + signaled_ = false; + return false; + } + + // We may get spurious wakeups. + TimeDelta wait_remaining = timeout; + TimePoint start = TimePoint::Now(); + while (true) { + if (std::cv_status::timeout == + cv_.wait_for(locker, + std::chrono::nanoseconds(wait_remaining.ToNanoseconds()))) + return true; // Definitely timed out. + + // We may have been awoken. + if (signaled_) + break; + + // Or the wakeup may have been spurious. + TimePoint now = TimePoint::Now(); + FML_DCHECK(now >= start); + TimeDelta elapsed = now - start; + // It's possible that we may have timed out anyway. + if (elapsed >= timeout) + return true; + + // Otherwise, recalculate the amount that we have left to wait. + wait_remaining = timeout - elapsed; + } + + signaled_ = false; + return false; +} + +bool AutoResetWaitableEvent::IsSignaledForTest() { + std::lock_guard locker(mutex_); + return signaled_; +} + +// ManualResetWaitableEvent ---------------------------------------------------- + +void ManualResetWaitableEvent::Signal() { + std::lock_guard locker(mutex_); + signaled_ = true; + signal_id_++; + cv_.notify_all(); +} + +void ManualResetWaitableEvent::Reset() { + std::lock_guard locker(mutex_); + signaled_ = false; +} + +void ManualResetWaitableEvent::Wait() { + std::unique_lock locker(mutex_); + + if (signaled_) + return; + + auto last_signal_id = signal_id_; + do { + cv_.wait(locker); + } while (signal_id_ == last_signal_id); +} + +bool ManualResetWaitableEvent::WaitWithTimeout(TimeDelta timeout) { + std::unique_lock locker(mutex_); + + auto last_signal_id = signal_id_; + // Disable thread-safety analysis for the lambda: We could annotate it with + // |FML_EXCLUSIVE_LOCKS_REQUIRED(mutex_)|, but then the analyzer currently + // isn't able to figure out that |WaitWithTimeoutImpl()| calls it while + // holding |mutex_|. + bool rv = WaitWithTimeoutImpl( + &locker, &cv_, + [this, last_signal_id]() FML_NO_THREAD_SAFETY_ANALYSIS { + // Also check |signaled_| in case we're already signaled. + return signaled_ || signal_id_ != last_signal_id; + }, + timeout); + FML_DCHECK(rv || signaled_ || signal_id_ != last_signal_id); + return rv; +} + +bool ManualResetWaitableEvent::IsSignaledForTest() { + std::lock_guard locker(mutex_); + return signaled_; +} + +} // namespace fml diff --git a/engine/src/flutter/fml/synchronization/waitable_event.h b/engine/src/flutter/fml/synchronization/waitable_event.h new file mode 100644 index 0000000000..60306aaa78 --- /dev/null +++ b/engine/src/flutter/fml/synchronization/waitable_event.h @@ -0,0 +1,128 @@ +// Copyright 2016 The Fuchsia Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Provides classes with functionality analogous to (but much more limited than) +// Chromium's |base::WaitableEvent|, which in turn provides functionality +// analogous to Windows's Event. (Unlike these two, we have separate types for +// the manual- and auto-reset versions.) + +#ifndef FLUTTER_FML_SYNCHRONIZATION_WAITABLE_EVENT_H_ +#define FLUTTER_FML_SYNCHRONIZATION_WAITABLE_EVENT_H_ + +#include +#include + +#include "flutter/fml/macros.h" +#include "flutter/fml/synchronization/thread_annotations.h" +#include "flutter/fml/time/time_delta.h" + +namespace fml { + +// AutoResetWaitableEvent ------------------------------------------------------ + +// An event that can be signaled and waited on. This version automatically +// returns to the unsignaled state after unblocking one waiter. (This is similar +// to Windows's auto-reset Event, which is also imitated by Chromium's +// auto-reset |base::WaitableEvent|. However, there are some limitations -- see +// |Signal()|.) This class is thread-safe. +class AutoResetWaitableEvent final { + public: + AutoResetWaitableEvent() {} + ~AutoResetWaitableEvent() {} + + // Put the event in the signaled state. Exactly one |Wait()| will be unblocked + // and the event will be returned to the unsignaled state. + // + // Notes (these are arguably bugs, but not worth working around): + // * That |Wait()| may be one that occurs on the calling thread, *after* the + // call to |Signal()|. + // * A |Signal()|, followed by a |Reset()|, may cause *no* waiting thread to + // be unblocked. + // * We rely on pthreads's queueing for picking which waiting thread to + // unblock, rather than enforcing FIFO ordering. + void Signal(); + + // Put the event into the unsignaled state. Generally, this is not recommended + // on an auto-reset event (see notes above). + void Reset(); + + // Blocks the calling thread until the event is signaled. Upon unblocking, the + // event is returned to the unsignaled state, so that (unless |Reset()| is + // called) each |Signal()| unblocks exactly one |Wait()|. + void Wait(); + + // Like |Wait()|, but with a timeout. Also unblocks if |timeout_microseconds| + // without being signaled in which case it returns true (otherwise, it returns + // false). + bool WaitWithTimeout(TimeDelta timeout); + + // Returns whether this event is in a signaled state or not. For use in tests + // only (in general, this is racy). Note: Unlike + // |base::WaitableEvent::IsSignaled()|, this doesn't reset the signaled state. + bool IsSignaledForTest(); + + private: + std::condition_variable cv_; + std::mutex mutex_; + + // True if this event is in the signaled state. + bool signaled_ = false; + + FML_DISALLOW_COPY_AND_ASSIGN(AutoResetWaitableEvent); +}; + +// ManualResetWaitableEvent ---------------------------------------------------- + +// An event that can be signaled and waited on. This version remains signaled +// until explicitly reset. (This is similar to Windows's manual-reset Event, +// which is also imitated by Chromium's manual-reset |base::WaitableEvent|.) +// This class is thread-safe. +class ManualResetWaitableEvent final { + public: + ManualResetWaitableEvent() {} + ~ManualResetWaitableEvent() {} + + // Put the event into the unsignaled state. + void Reset(); + + // Put the event in the signaled state. If this is a manual-reset event, it + // wakes all waiting threads (blocked on |Wait()| or |WaitWithTimeout()|). + // Otherwise, it wakes a single waiting thread (and returns to the unsignaled + // state), if any; if there are none, it remains signaled. + void Signal(); + + // Blocks the calling thread until the event is signaled. + void Wait(); + + // Like |Wait()|, but with a timeout. Also unblocks if |timeout_microseconds| + // without being signaled in which case it returns true (otherwise, it returns + // false). + bool WaitWithTimeout(TimeDelta timeout); + + // Returns whether this event is in a signaled state or not. For use in tests + // only (in general, this is racy). + bool IsSignaledForTest(); + + private: + std::condition_variable cv_; + std::mutex mutex_; + + // True if this event is in the signaled state. + bool signaled_ = false; + + // While |std::condition_variable::notify_all()| (|pthread_cond_broadcast()|) + // will wake all waiting threads, one has to deal with spurious wake-ups. + // Checking |signaled_| isn't sufficient, since another thread may have been + // awoken and (manually) reset |signaled_|. This is a counter that is + // incremented in |Signal()| before calling + // |std::condition_variable::notify_all()|. A waiting thread knows it was + // awoken if |signal_id_| is different from when it started waiting. + unsigned signal_id_ = 0u; + + FML_DISALLOW_COPY_AND_ASSIGN(ManualResetWaitableEvent); +}; + +} // namespace fml + +#endif // FLUTTER_FML_SYNCHRONIZATION_WAITABLE_EVENT_H_ diff --git a/engine/src/flutter/fml/synchronization/waitable_event_unittest.cc b/engine/src/flutter/fml/synchronization/waitable_event_unittest.cc new file mode 100644 index 0000000000..92f40577dc --- /dev/null +++ b/engine/src/flutter/fml/synchronization/waitable_event_unittest.cc @@ -0,0 +1,187 @@ +// Copyright 2016 The Fuchsia Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "flutter/fml/synchronization/waitable_event.h" + +#include +#include +#include + +#include +#include +#include +#include + +#include "flutter/fml/macros.h" +#include "gtest/gtest.h" + +#ifndef arraysize +template +char (&ArraySizeHelper(T (&array)[N]))[N]; +#define arraysize(array) (sizeof(ArraySizeHelper(array))) +#endif + +namespace fml { +namespace { + +constexpr TimeDelta kEpsilonTimeout = TimeDelta::FromMilliseconds(20); +constexpr TimeDelta kTinyTimeout = TimeDelta::FromMilliseconds(100); +constexpr TimeDelta kActionTimeout = TimeDelta::FromMilliseconds(10000); + +// Sleeps for a "very small" amount of time. + +void SleepFor(TimeDelta duration) { + std::this_thread::sleep_for( + std::chrono::nanoseconds(duration.ToNanoseconds())); +} + +void EpsilonRandomSleep() { + TimeDelta duration = + TimeDelta::FromMilliseconds(static_cast(rand()) % 20u); + SleepFor(duration); +} + +// AutoResetWaitableEvent ------------------------------------------------------ + +TEST(AutoResetWaitableEventTest, Basic) { + AutoResetWaitableEvent ev; + EXPECT_FALSE(ev.IsSignaledForTest()); + ev.Signal(); + EXPECT_TRUE(ev.IsSignaledForTest()); + ev.Wait(); + EXPECT_FALSE(ev.IsSignaledForTest()); + ev.Reset(); + EXPECT_FALSE(ev.IsSignaledForTest()); + ev.Signal(); + EXPECT_TRUE(ev.IsSignaledForTest()); + ev.Reset(); + EXPECT_FALSE(ev.IsSignaledForTest()); + EXPECT_TRUE(ev.WaitWithTimeout(TimeDelta::Zero())); + EXPECT_FALSE(ev.IsSignaledForTest()); + EXPECT_TRUE(ev.WaitWithTimeout(TimeDelta::FromMilliseconds(1))); + EXPECT_FALSE(ev.IsSignaledForTest()); + ev.Signal(); + EXPECT_TRUE(ev.IsSignaledForTest()); + EXPECT_FALSE(ev.WaitWithTimeout(TimeDelta::Zero())); + EXPECT_FALSE(ev.IsSignaledForTest()); + EXPECT_TRUE(ev.WaitWithTimeout(TimeDelta::FromMilliseconds(1))); + EXPECT_FALSE(ev.IsSignaledForTest()); + ev.Signal(); + EXPECT_FALSE(ev.WaitWithTimeout(TimeDelta::FromMilliseconds(1))); + EXPECT_FALSE(ev.IsSignaledForTest()); +} + +TEST(AutoResetWaitableEventTest, MultipleWaiters) { + AutoResetWaitableEvent ev; + + for (size_t i = 0u; i < 5u; i++) { + std::atomic_uint wake_count(0u); + std::vector threads; + for (size_t j = 0u; j < 4u; j++) { + threads.push_back(std::thread([&ev, &wake_count]() { + if (rand() % 2 == 0) + ev.Wait(); + else + EXPECT_FALSE(ev.WaitWithTimeout(kActionTimeout)); + wake_count.fetch_add(1u); + // Note: We can't say anything about the signaled state of |ev| here, + // since the main thread may have already signaled it again. + })); + } + + // Unfortunately, we can't really wait for the threads to be waiting, so we + // just sleep for a bit, and count on them having started and advanced to + // waiting. + SleepFor(kTinyTimeout + kTinyTimeout); + + for (size_t j = 0u; j < threads.size(); j++) { + unsigned old_wake_count = wake_count.load(); + EXPECT_EQ(j, old_wake_count); + + // Each |Signal()| should wake exactly one thread. + ev.Signal(); + + // Poll for |wake_count| to change. + while (wake_count.load() == old_wake_count) + SleepFor(kEpsilonTimeout); + + EXPECT_FALSE(ev.IsSignaledForTest()); + + // And once it's changed, wait a little longer, to see if any other + // threads are awoken (they shouldn't be). + SleepFor(kEpsilonTimeout); + + EXPECT_EQ(old_wake_count + 1u, wake_count.load()); + + EXPECT_FALSE(ev.IsSignaledForTest()); + } + + // Having done that, if we signal |ev| now, it should stay signaled. + ev.Signal(); + SleepFor(kEpsilonTimeout); + EXPECT_TRUE(ev.IsSignaledForTest()); + + for (auto& thread : threads) + thread.join(); + + ev.Reset(); + } +} + +// ManualResetWaitableEvent ---------------------------------------------------- + +TEST(ManualResetWaitableEventTest, Basic) { + ManualResetWaitableEvent ev; + EXPECT_FALSE(ev.IsSignaledForTest()); + ev.Signal(); + EXPECT_TRUE(ev.IsSignaledForTest()); + ev.Wait(); + EXPECT_TRUE(ev.IsSignaledForTest()); + ev.Reset(); + EXPECT_FALSE(ev.IsSignaledForTest()); + EXPECT_TRUE(ev.WaitWithTimeout(TimeDelta::Zero())); + EXPECT_FALSE(ev.IsSignaledForTest()); + EXPECT_TRUE(ev.WaitWithTimeout(TimeDelta::FromMilliseconds(1))); + EXPECT_FALSE(ev.IsSignaledForTest()); + ev.Signal(); + EXPECT_TRUE(ev.IsSignaledForTest()); + EXPECT_FALSE(ev.WaitWithTimeout(TimeDelta::Zero())); + EXPECT_TRUE(ev.IsSignaledForTest()); + EXPECT_FALSE(ev.WaitWithTimeout(TimeDelta::FromMilliseconds(1))); + EXPECT_TRUE(ev.IsSignaledForTest()); +} + +TEST(ManualResetWaitableEventTest, SignalMultiple) { + ManualResetWaitableEvent ev; + + for (size_t i = 0u; i < 10u; i++) { + for (size_t num_waiters = 1u; num_waiters < 5u; num_waiters++) { + std::vector threads; + for (size_t j = 0u; j < num_waiters; j++) { + threads.push_back(std::thread([&ev]() { + EpsilonRandomSleep(); + + if (rand() % 2 == 0) + ev.Wait(); + else + EXPECT_FALSE(ev.WaitWithTimeout(kActionTimeout)); + })); + } + + EpsilonRandomSleep(); + + ev.Signal(); + + // The threads will only terminate once they've successfully waited (or + // timed out). + for (auto& thread : threads) + thread.join(); + + ev.Reset(); + } + } +} + +} // namespace +} // namespace fml