1 /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
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 http://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
16 #ifndef TENSORFLOW_CORE_PLATFORM_DEFAULT_NOTIFICATION_H_
17 #define TENSORFLOW_CORE_PLATFORM_DEFAULT_NOTIFICATION_H_
18
19 #include <assert.h>
20 #include <atomic> // NOLINT
21 #include <chrono> // NOLINT
22 #include <condition_variable> // NOLINT
23
24 #include "tensorflow/core/platform/mutex.h"
25 #include "tensorflow/core/platform/types.h"
26
27 namespace tensorflow {
28
29 class Notification {
30 public:
Notification()31 Notification() : notified_(0) {}
~Notification()32 ~Notification() {
33 // In case the notification is being used to synchronize its own deletion,
34 // force any prior notifier to leave its critical section before the object
35 // is destroyed.
36 mutex_lock l(mu_);
37 }
38
Notify()39 void Notify() {
40 mutex_lock l(mu_);
41 assert(!HasBeenNotified());
42 notified_.store(true, std::memory_order_release);
43 cv_.notify_all();
44 }
45
HasBeenNotified()46 bool HasBeenNotified() const {
47 return notified_.load(std::memory_order_acquire);
48 }
49
WaitForNotification()50 void WaitForNotification() {
51 if (!HasBeenNotified()) {
52 mutex_lock l(mu_);
53 while (!HasBeenNotified()) {
54 cv_.wait(l);
55 }
56 }
57 }
58
59 private:
60 friend bool WaitForNotificationWithTimeout(Notification* n,
61 int64 timeout_in_us);
WaitForNotificationWithTimeout(int64 timeout_in_us)62 bool WaitForNotificationWithTimeout(int64 timeout_in_us) {
63 bool notified = HasBeenNotified();
64 if (!notified) {
65 mutex_lock l(mu_);
66 do {
67 notified = HasBeenNotified();
68 } while (!notified &&
69 cv_.wait_for(l, std::chrono::microseconds(timeout_in_us)) !=
70 std::cv_status::timeout);
71 }
72 return notified;
73 }
74
75 mutex mu_; // protects mutations of notified_
76 condition_variable cv_; // signaled when notified_ becomes non-zero
77 std::atomic<bool> notified_; // mutations under mu_
78 };
79
WaitForNotificationWithTimeout(Notification * n,int64 timeout_in_us)80 inline bool WaitForNotificationWithTimeout(Notification* n,
81 int64 timeout_in_us) {
82 return n->WaitForNotificationWithTimeout(timeout_in_us);
83 }
84
85 } // namespace tensorflow
86
87 #endif // TENSORFLOW_CORE_PLATFORM_DEFAULT_NOTIFICATION_H_
88