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/attributes.h"
20 #include "absl/base/internal/raw_logging.h"
21 #include "absl/synchronization/mutex.h"
22 #include "absl/time/time.h"
23 
24 namespace absl {
25 ABSL_NAMESPACE_BEGIN
26 
Notify()27 void Notification::Notify() {
28   MutexLock l(&this->mutex_);
29 
30 #ifndef NDEBUG
31   if (ABSL_PREDICT_FALSE(notified_yet_.load(std::memory_order_relaxed))) {
32     ABSL_RAW_LOG(
33         FATAL,
34         "Notify() method called more than once for Notification object %p",
35         static_cast<void *>(this));
36   }
37 #endif
38 
39   notified_yet_.store(true, std::memory_order_release);
40 }
41 
~Notification()42 Notification::~Notification() {
43   // Make sure that the thread running Notify() exits before the object is
44   // destructed.
45   MutexLock l(&this->mutex_);
46 }
47 
WaitForNotification() const48 void Notification::WaitForNotification() const {
49   if (!HasBeenNotifiedInternal(&this->notified_yet_)) {
50     this->mutex_.LockWhen(Condition(&HasBeenNotifiedInternal,
51                                     &this->notified_yet_));
52     this->mutex_.Unlock();
53   }
54 }
55 
WaitForNotificationWithTimeout(absl::Duration timeout) const56 bool Notification::WaitForNotificationWithTimeout(
57     absl::Duration timeout) const {
58   bool notified = HasBeenNotifiedInternal(&this->notified_yet_);
59   if (!notified) {
60     notified = this->mutex_.LockWhenWithTimeout(
61         Condition(&HasBeenNotifiedInternal, &this->notified_yet_), timeout);
62     this->mutex_.Unlock();
63   }
64   return notified;
65 }
66 
WaitForNotificationWithDeadline(absl::Time deadline) const67 bool Notification::WaitForNotificationWithDeadline(absl::Time deadline) const {
68   bool notified = HasBeenNotifiedInternal(&this->notified_yet_);
69   if (!notified) {
70     notified = this->mutex_.LockWhenWithDeadline(
71         Condition(&HasBeenNotifiedInternal, &this->notified_yet_), deadline);
72     this->mutex_.Unlock();
73   }
74   return notified;
75 }
76 
77 ABSL_NAMESPACE_END
78 }  // namespace absl
79