Optimizing OneShotTimer::reset() function

When running simpleperf, reset() function caused every once
in a while locks, which we suspect cause occasional janking.

- Moving the state to atomic, so there is no time spent
  acquiring the lock.
- When using condition_variable, atomic still needs to be
  changed under mutex, so moving to semaphores to guard
  and signal.

See b/170665374 for analysis report.

Bug: 170665374
Test: atest DisplayMicrobenchTests while running simple perf
Test: atest OneShotTimerTest
Change-Id: Ic450ea074bc07175c3fc681b69a8009be84d30a0
diff --git a/services/surfaceflinger/Scheduler/OneShotTimer.h b/services/surfaceflinger/Scheduler/OneShotTimer.h
index b005754..8bbd4f5 100644
--- a/services/surfaceflinger/Scheduler/OneShotTimer.h
+++ b/services/surfaceflinger/Scheduler/OneShotTimer.h
@@ -16,6 +16,7 @@
 
 #pragma once
 
+#include <semaphore.h>
 #include <chrono>
 #include <condition_variable>
 #include <thread>
@@ -70,17 +71,15 @@
     // Function that loops until the condition for stopping is met.
     void loop();
 
+    // Checks whether mResetTriggered and mStopTriggered were set and updates
+    // mState if so.
+    TimerState checkForResetAndStop(TimerState state);
+
     // Thread waiting for timer to expire.
     std::thread mThread;
 
-    // Condition used to notify mThread.
-    std::condition_variable_any mCondition;
-
-    // Lock used for synchronizing the waiting thread with the application thread.
-    std::mutex mMutex;
-
-    // Current timer state
-    TimerState mState GUARDED_BY(mMutex) = TimerState::RESET;
+    // Semaphore to keep mThread synchronized.
+    sem_t mSemaphore;
 
     // Interval after which timer expires.
     const Interval mInterval;
@@ -90,6 +89,12 @@
 
     // Callback that happens when timer expires.
     const TimeoutCallback mTimeoutCallback;
+
+    // After removing lock guarding mState, the state can be now accessed at
+    // any time. Keep a bool if the reset or stop were requested, and occasionally
+    // check in the main loop if they were.
+    std::atomic<bool> mResetTriggered = false;
+    std::atomic<bool> mStopTriggered = false;
 };
 
 } // namespace scheduler