• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2024 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "base/synchronization/cancelable_event.h"
6 
7 #include <windows.h>
8 
9 #include <synchapi.h>
10 #include <winbase.h>
11 
12 #include <tuple>
13 
14 #include "base/synchronization/lock.h"
15 
16 namespace base {
17 
CancelableEvent()18 CancelableEvent::CancelableEvent() {
19   native_handle_ = ::CreateSemaphoreA(nullptr, 0, 1, nullptr);
20   PCHECK(!!native_handle_);
21 }
22 
~CancelableEvent()23 CancelableEvent::~CancelableEvent() {
24   const bool result = ::CloseHandle(native_handle_);
25   PCHECK(result);
26 }
27 
SignalImpl()28 void CancelableEvent::SignalImpl() {
29   LONG prev_count;
30   const bool result = ::ReleaseSemaphore(native_handle_, 1, &prev_count);
31   PCHECK(result);
32   CHECK_EQ(prev_count, 0);
33 }
34 
CancelImpl()35 bool CancelableEvent::CancelImpl() {
36   const DWORD result = ::WaitForSingleObject(native_handle_, 0);
37   return result == WAIT_OBJECT_0;
38 }
39 
TimedWaitImpl(TimeDelta timeout)40 bool CancelableEvent::TimedWaitImpl(TimeDelta timeout) {
41   const DWORD wait_ms = saturated_cast<DWORD>(timeout.InMilliseconds());
42   const TimeTicks start = TimeTicks::Now();
43   DWORD result;
44   // WaitForSingleObject has been shown to experience spurious wakeups (on the
45   // order of 10ms before when it was supposed to wake up), so retry until at
46   // least `timeout` has passed.
47   do {
48     result = ::WaitForSingleObject(native_handle_, wait_ms);
49     if (result == WAIT_OBJECT_0) {
50       return true;
51     }
52   } while (TimeTicks::Now() <= start + timeout);
53   CHECK_EQ(result, static_cast<DWORD>(WAIT_TIMEOUT));
54   return false;
55 }
56 
57 }  // namespace base
58