• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2022 The gRPC 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 //     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 #ifndef GRPC_SRC_CORE_UTIL_NOTIFICATION_H
16 #define GRPC_SRC_CORE_UTIL_NOTIFICATION_H
17 
18 #include <grpc/support/port_platform.h>
19 
20 #include "absl/time/clock.h"
21 #include "absl/time/time.h"
22 #include "src/core/util/sync.h"
23 
24 namespace grpc_core {
25 
26 // Polyfill for absl::Notification until we can use that type.
27 class Notification {
28  public:
Notify()29   void Notify() {
30     MutexLock lock(&mu_);
31     notified_ = true;
32     cv_.SignalAll();
33   }
34 
WaitForNotification()35   void WaitForNotification() {
36     MutexLock lock(&mu_);
37     while (!notified_) {
38       cv_.Wait(&mu_);
39     }
40   }
41 
WaitForNotificationWithTimeout(absl::Duration timeout)42   bool WaitForNotificationWithTimeout(absl::Duration timeout) {
43     auto now = absl::Now();
44     auto deadline = now + timeout;
45     MutexLock lock(&mu_);
46     while (!notified_ && now < deadline) {
47       cv_.WaitWithTimeout(&mu_, deadline - now);
48       now = absl::Now();
49     }
50     return notified_;
51   }
52 
HasBeenNotified()53   bool HasBeenNotified() {
54     MutexLock lock(&mu_);
55     return notified_;
56   }
57 
58  private:
59   Mutex mu_;
60   CondVar cv_;
61   bool notified_ = false;
62 };
63 
64 }  // namespace grpc_core
65 
66 #endif  // GRPC_SRC_CORE_UTIL_NOTIFICATION_H
67