3 * Copyright 2019 gRPC authors.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
19 #ifndef GRPC_CORE_LIB_GPRPP_SYNC_H
20 #define GRPC_CORE_LIB_GPRPP_SYNC_H
22 #include <grpc/impl/codegen/port_platform.h>
24 #include <grpc/impl/codegen/log.h>
25 #include <grpc/impl/codegen/sync.h>
26 #include <grpc/support/sync.h>
27 #include <grpc/support/time.h>
29 // The core library is not accessible in C++ codegen headers, and vice versa.
30 // Thus, we need to have duplicate headers with similar functionality.
31 // Make sure any change to this file is also reflected in
32 // include/grpcpp/impl/codegen/sync.h.
34 // Whenever possible, prefer using this file over <grpcpp/impl/codegen/sync.h>
35 // since this file doesn't rely on g_core_codegen_interface and hence does not
36 // pay the costs of virtual function calls.
42 Mutex() { gpr_mu_init(&mu_); }
43 ~Mutex() { gpr_mu_destroy(&mu_); }
45 Mutex(const Mutex&) = delete;
46 Mutex& operator=(const Mutex&) = delete;
48 gpr_mu* get() { return &mu_; }
49 const gpr_mu* get() const { return &mu_; }
55 // MutexLock is a std::
58 explicit MutexLock(Mutex* mu) : mu_(mu->get()) { gpr_mu_lock(mu_); }
59 explicit MutexLock(gpr_mu* mu) : mu_(mu) { gpr_mu_lock(mu_); }
60 ~MutexLock() { gpr_mu_unlock(mu_); }
62 MutexLock(const MutexLock&) = delete;
63 MutexLock& operator=(const MutexLock&) = delete;
69 class ReleasableMutexLock {
71 explicit ReleasableMutexLock(Mutex* mu) : mu_(mu->get()) { gpr_mu_lock(mu_); }
72 explicit ReleasableMutexLock(gpr_mu* mu) : mu_(mu) { gpr_mu_lock(mu_); }
73 ~ReleasableMutexLock() {
74 if (!released_) gpr_mu_unlock(mu_);
77 ReleasableMutexLock(const ReleasableMutexLock&) = delete;
78 ReleasableMutexLock& operator=(const ReleasableMutexLock&) = delete;
81 GPR_DEBUG_ASSERT(released_);
87 GPR_DEBUG_ASSERT(!released_);
94 bool released_ = false;
99 CondVar() { gpr_cv_init(&cv_); }
100 ~CondVar() { gpr_cv_destroy(&cv_); }
102 CondVar(const CondVar&) = delete;
103 CondVar& operator=(const CondVar&) = delete;
105 void Signal() { gpr_cv_signal(&cv_); }
106 void Broadcast() { gpr_cv_broadcast(&cv_); }
108 int Wait(Mutex* mu) { return Wait(mu, gpr_inf_future(GPR_CLOCK_REALTIME)); }
109 int Wait(Mutex* mu, const gpr_timespec& deadline) {
110 return gpr_cv_wait(&cv_, mu->get(), deadline);
113 template <typename Predicate>
114 void WaitUntil(Mutex* mu, Predicate pred) {
116 Wait(mu, gpr_inf_future(GPR_CLOCK_REALTIME));
124 } // namespace grpc_core
126 #endif /* GRPC_CORE_LIB_GPRPP_SYNC_H */