16 #ifndef TENSORFLOW_SERVING_UTIL_OBSERVER_H_
17 #define TENSORFLOW_SERVING_UTIL_OBSERVER_H_
24 #include "tensorflow/core/platform/logging.h"
25 #include "tensorflow/core/platform/macros.h"
26 #include "tensorflow/core/platform/mutex.h"
27 #include "tensorflow/core/platform/thread_annotations.h"
28 #include "tensorflow/core/platform/types.h"
30 namespace tensorflow {
59 template <
typename... Args>
63 using Function = std::function<void(Args...)>;
66 explicit Observer(Function f) : impl_(std::make_shared<Impl>(std::move(f))) {}
70 if (impl_ !=
nullptr) {
77 Function Notifier()
const {
79 DCHECK(impl !=
nullptr);
80 return [impl](Args... args) { impl->Notify(std::forward<Args>(args)...); };
84 template <
typename... T>
91 std::shared_ptr<Impl> impl_;
93 TF_DISALLOW_COPY_AND_ASSIGN(
Observer);
98 template <
typename... Args>
104 for (
auto& observer : observers_) {
105 if (observer->IsOrphaned()) {
106 observer = new_observer.impl_;
110 observers_.push_back(new_observer.impl_);
114 void Notify(Args... args) {
115 for (
const auto& observer : observers_) {
116 observer->Notify(std::forward<Args>(args)...);
121 void Clear() { observers_.clear(); }
125 std::vector<std::shared_ptr<
typename Observer<Args...>::Impl>> observers_;
131 template <
typename... Args>
134 explicit Impl(Function f) : f_(std::move(f)) {}
136 bool IsOrphaned()
const {
137 mutex_lock lock(mutex_);
138 return f_ ==
nullptr;
142 mutex_lock lock(mutex_);
146 void Notify(Args... args)
const {
147 mutex_lock lock(mutex_);
149 f_(std::forward<Args>(args)...);
154 mutable mutex mutex_;
156 Function f_ TF_GUARDED_BY(mutex_);