Debian Codegraph @

src/core/lib/gprpp/notification.h

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