1/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
2
3Licensed under the Apache License, Version 2.0 (the "License");
4you may not use this file except in compliance with the License.
5You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9Unless required by applicable law or agreed to in writing, software
10distributed under the License is distributed on an "AS IS" BASIS,
11WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12See the License for the specific language governing permissions and
13limitations under the License.
14==============================================================================*/
15
16#ifndef TENSORFLOW_TSL_PLATFORM_DEFAULT_NOTIFICATION_H_
17#define TENSORFLOW_TSL_PLATFORM_DEFAULT_NOTIFICATION_H_
18
19#include <assert.h>
20
21#include <atomic> // NOLINT
22#include <chrono> // NOLINT
23#include <condition_variable> // NOLINT
24
25#include "tensorflow/tsl/platform/mutex.h"
26#include "tensorflow/tsl/platform/types.h"
27
28namespace tsl {
29
30class Notification {
31 public:
32 Notification() : notified_(0) {}
33 ~Notification() {
34 // In case the notification is being used to synchronize its own deletion,
35 // force any prior notifier to leave its critical section before the object
36 // is destroyed.
37 mutex_lock l(mu_);
38 }
39
40 void Notify() {
41 mutex_lock l(mu_);
42 assert(!HasBeenNotified());
43 notified_.store(true, std::memory_order_release);
44 cv_.notify_all();
45 }
46
47 bool HasBeenNotified() const {
48 return notified_.load(std::memory_order_acquire);
49 }
50
51 void WaitForNotification() {
52 if (!HasBeenNotified()) {
53 mutex_lock l(mu_);
54 while (!HasBeenNotified()) {
55 cv_.wait(l);
56 }
57 }
58 }
59
60 private:
61 friend bool WaitForNotificationWithTimeout(Notification* n,
62 int64_t timeout_in_us);
63 bool WaitForNotificationWithTimeout(int64_t timeout_in_us) {
64 bool notified = HasBeenNotified();
65 if (!notified) {
66 mutex_lock l(mu_);
67 do {
68 notified = HasBeenNotified();
69 } while (!notified &&
70 cv_.wait_for(l, std::chrono::microseconds(timeout_in_us)) !=
71 std::cv_status::timeout);
72 }
73 return notified;
74 }
75
76 mutex mu_; // protects mutations of notified_
77 condition_variable cv_; // signaled when notified_ becomes non-zero
78 std::atomic<bool> notified_; // mutations under mu_
79};
80
81inline bool WaitForNotificationWithTimeout(Notification* n,
82 int64_t timeout_in_us) {
83 return n->WaitForNotificationWithTimeout(timeout_in_us);
84}
85
86} // namespace tsl
87
88#endif // TENSORFLOW_TSL_PLATFORM_DEFAULT_NOTIFICATION_H_
89