xref: /aosp_15_r20/external/webrtc/rtc_base/event.cc (revision d9f758449e529ab9291ac668be2861e7a55c2422)
1 /*
2  *  Copyright 2004 The WebRTC Project Authors. All rights reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 #include "rtc_base/event.h"
12 
13 #if defined(WEBRTC_WIN)
14 #include <windows.h>
15 #elif defined(WEBRTC_POSIX)
16 #include <errno.h>
17 #include <pthread.h>
18 #include <sys/time.h>
19 #include <time.h>
20 #else
21 #error "Must define either WEBRTC_WIN or WEBRTC_POSIX."
22 #endif
23 
24 #include "absl/types/optional.h"
25 #include "rtc_base/checks.h"
26 #include "rtc_base/synchronization/yield_policy.h"
27 #include "rtc_base/system/warn_current_thread_is_deadlocked.h"
28 #include "rtc_base/time_utils.h"
29 
30 namespace rtc {
31 
32 using ::webrtc::TimeDelta;
33 
Event()34 Event::Event() : Event(false, false) {}
35 
36 #if defined(WEBRTC_WIN)
37 
Event(bool manual_reset,bool initially_signaled)38 Event::Event(bool manual_reset, bool initially_signaled) {
39   event_handle_ = ::CreateEvent(nullptr,  // Security attributes.
40                                 manual_reset, initially_signaled,
41                                 nullptr);  // Name.
42   RTC_CHECK(event_handle_);
43 }
44 
~Event()45 Event::~Event() {
46   CloseHandle(event_handle_);
47 }
48 
Set()49 void Event::Set() {
50   SetEvent(event_handle_);
51 }
52 
Reset()53 void Event::Reset() {
54   ResetEvent(event_handle_);
55 }
56 
Wait(TimeDelta give_up_after,TimeDelta)57 bool Event::Wait(TimeDelta give_up_after, TimeDelta /*warn_after*/) {
58   ScopedYieldPolicy::YieldExecution();
59   const DWORD ms =
60       give_up_after.IsPlusInfinity()
61           ? INFINITE
62           : give_up_after.RoundUpTo(webrtc::TimeDelta::Millis(1)).ms();
63   return (WaitForSingleObject(event_handle_, ms) == WAIT_OBJECT_0);
64 }
65 
66 #elif defined(WEBRTC_POSIX)
67 
68 // On MacOS, clock_gettime is available from version 10.12, and on
69 // iOS, from version 10.0. So we can't use it yet.
70 #if defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
71 #define USE_CLOCK_GETTIME 0
72 #define USE_PTHREAD_COND_TIMEDWAIT_MONOTONIC_NP 0
73 // On Android, pthread_condattr_setclock is available from version 21. By
74 // default, we target a new enough version for 64-bit platforms but not for
75 // 32-bit platforms. For older versions, use
76 // pthread_cond_timedwait_monotonic_np.
77 #elif defined(WEBRTC_ANDROID) && (__ANDROID_API__ < 21)
78 #define USE_CLOCK_GETTIME 1
79 #define USE_PTHREAD_COND_TIMEDWAIT_MONOTONIC_NP 1
80 #else
81 #define USE_CLOCK_GETTIME 1
82 #define USE_PTHREAD_COND_TIMEDWAIT_MONOTONIC_NP 0
83 #endif
84 
Event(bool manual_reset,bool initially_signaled)85 Event::Event(bool manual_reset, bool initially_signaled)
86     : is_manual_reset_(manual_reset), event_status_(initially_signaled) {
87   RTC_CHECK(pthread_mutex_init(&event_mutex_, nullptr) == 0);
88   pthread_condattr_t cond_attr;
89   RTC_CHECK(pthread_condattr_init(&cond_attr) == 0);
90 #if USE_CLOCK_GETTIME && !USE_PTHREAD_COND_TIMEDWAIT_MONOTONIC_NP
91   RTC_CHECK(pthread_condattr_setclock(&cond_attr, CLOCK_MONOTONIC) == 0);
92 #endif
93   RTC_CHECK(pthread_cond_init(&event_cond_, &cond_attr) == 0);
94   pthread_condattr_destroy(&cond_attr);
95 }
96 
~Event()97 Event::~Event() {
98   pthread_mutex_destroy(&event_mutex_);
99   pthread_cond_destroy(&event_cond_);
100 }
101 
Set()102 void Event::Set() {
103   pthread_mutex_lock(&event_mutex_);
104   event_status_ = true;
105   pthread_cond_broadcast(&event_cond_);
106   pthread_mutex_unlock(&event_mutex_);
107 }
108 
Reset()109 void Event::Reset() {
110   pthread_mutex_lock(&event_mutex_);
111   event_status_ = false;
112   pthread_mutex_unlock(&event_mutex_);
113 }
114 
115 namespace {
116 
GetTimespec(TimeDelta duration_from_now)117 timespec GetTimespec(TimeDelta duration_from_now) {
118   timespec ts;
119 
120   // Get the current time.
121 #if USE_CLOCK_GETTIME
122   clock_gettime(CLOCK_MONOTONIC, &ts);
123 #else
124   timeval tv;
125   gettimeofday(&tv, nullptr);
126   ts.tv_sec = tv.tv_sec;
127   ts.tv_nsec = tv.tv_usec * kNumNanosecsPerMicrosec;
128 #endif
129 
130   // Add the specified number of milliseconds to it.
131   int64_t microsecs_from_now = duration_from_now.us();
132   ts.tv_sec += microsecs_from_now / kNumMicrosecsPerSec;
133   ts.tv_nsec +=
134       (microsecs_from_now % kNumMicrosecsPerSec) * kNumNanosecsPerMicrosec;
135 
136   // Normalize.
137   if (ts.tv_nsec >= kNumNanosecsPerSec) {
138     ts.tv_sec++;
139     ts.tv_nsec -= kNumNanosecsPerSec;
140   }
141 
142   return ts;
143 }
144 
145 }  // namespace
146 
Wait(TimeDelta give_up_after,TimeDelta warn_after)147 bool Event::Wait(TimeDelta give_up_after, TimeDelta warn_after) {
148   // Instant when we'll log a warning message (because we've been waiting so
149   // long it might be a bug), but not yet give up waiting. nullopt if we
150   // shouldn't log a warning.
151   const absl::optional<timespec> warn_ts =
152       warn_after >= give_up_after
153           ? absl::nullopt
154           : absl::make_optional(GetTimespec(warn_after));
155 
156   // Instant when we'll stop waiting and return an error. nullopt if we should
157   // never give up.
158   const absl::optional<timespec> give_up_ts =
159       give_up_after.IsPlusInfinity()
160           ? absl::nullopt
161           : absl::make_optional(GetTimespec(give_up_after));
162 
163   ScopedYieldPolicy::YieldExecution();
164   pthread_mutex_lock(&event_mutex_);
165 
166   // Wait for `event_cond_` to trigger and `event_status_` to be set, with the
167   // given timeout (or without a timeout if none is given).
168   const auto wait = [&](const absl::optional<timespec> timeout_ts) {
169     int error = 0;
170     while (!event_status_ && error == 0) {
171       if (timeout_ts == absl::nullopt) {
172         error = pthread_cond_wait(&event_cond_, &event_mutex_);
173       } else {
174 #if USE_PTHREAD_COND_TIMEDWAIT_MONOTONIC_NP
175         error = pthread_cond_timedwait_monotonic_np(&event_cond_, &event_mutex_,
176                                                     &*timeout_ts);
177 #else
178         error =
179             pthread_cond_timedwait(&event_cond_, &event_mutex_, &*timeout_ts);
180 #endif
181       }
182     }
183     return error;
184   };
185 
186   int error;
187   if (warn_ts == absl::nullopt) {
188     error = wait(give_up_ts);
189   } else {
190     error = wait(warn_ts);
191     if (error == ETIMEDOUT) {
192       webrtc::WarnThatTheCurrentThreadIsProbablyDeadlocked();
193       error = wait(give_up_ts);
194     }
195   }
196 
197   // NOTE(liulk): Exactly one thread will auto-reset this event. All
198   // the other threads will think it's unsignaled.  This seems to be
199   // consistent with auto-reset events in WEBRTC_WIN
200   if (error == 0 && !is_manual_reset_)
201     event_status_ = false;
202 
203   pthread_mutex_unlock(&event_mutex_);
204 
205   return (error == 0);
206 }
207 
208 #endif
209 
210 }  // namespace rtc
211