xref: /aosp_15_r20/external/abseil-cpp/absl/synchronization/notification.cc (revision 9356374a3709195abf420251b3e825997ff56c0f)
1 // Copyright 2017 The Abseil Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "absl/synchronization/notification.h"
16 
17 #include <atomic>
18 
19 #include "absl/base/internal/raw_logging.h"
20 #include "absl/synchronization/mutex.h"
21 #include "absl/time/time.h"
22 
23 namespace absl {
24 ABSL_NAMESPACE_BEGIN
25 
Notify()26 void Notification::Notify() {
27   MutexLock l(&this->mutex_);
28 
29 #ifndef NDEBUG
30   if (ABSL_PREDICT_FALSE(notified_yet_.load(std::memory_order_relaxed))) {
31     ABSL_RAW_LOG(
32         FATAL,
33         "Notify() method called more than once for Notification object %p",
34         static_cast<void *>(this));
35   }
36 #endif
37 
38   notified_yet_.store(true, std::memory_order_release);
39 }
40 
~Notification()41 Notification::~Notification() {
42   // Make sure that the thread running Notify() exits before the object is
43   // destructed.
44   MutexLock l(&this->mutex_);
45 }
46 
WaitForNotification() const47 void Notification::WaitForNotification() const {
48   if (!HasBeenNotifiedInternal(&this->notified_yet_)) {
49     this->mutex_.LockWhen(Condition(&HasBeenNotifiedInternal,
50                                     &this->notified_yet_));
51     this->mutex_.Unlock();
52   }
53 }
54 
WaitForNotificationWithTimeout(absl::Duration timeout) const55 bool Notification::WaitForNotificationWithTimeout(
56     absl::Duration timeout) const {
57   bool notified = HasBeenNotifiedInternal(&this->notified_yet_);
58   if (!notified) {
59     notified = this->mutex_.LockWhenWithTimeout(
60         Condition(&HasBeenNotifiedInternal, &this->notified_yet_), timeout);
61     this->mutex_.Unlock();
62   }
63   return notified;
64 }
65 
WaitForNotificationWithDeadline(absl::Time deadline) const66 bool Notification::WaitForNotificationWithDeadline(absl::Time deadline) const {
67   bool notified = HasBeenNotifiedInternal(&this->notified_yet_);
68   if (!notified) {
69     notified = this->mutex_.LockWhenWithDeadline(
70         Condition(&HasBeenNotifiedInternal, &this->notified_yet_), deadline);
71     this->mutex_.Unlock();
72   }
73   return notified;
74 }
75 
76 ABSL_NAMESPACE_END
77 }  // namespace absl
78