atomic_utils.h
Go to the documentation of this file.
1 /*
2  *
3  * Copyright 2017 gRPC authors.
4  *
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
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
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.
16  *
17  */
18 
19 #ifndef GRPC_CORE_LIB_GPRPP_ATOMIC_UTILS_H
20 #define GRPC_CORE_LIB_GPRPP_ATOMIC_UTILS_H
21 
23 
24 #include <atomic>
25 
26 namespace grpc_core {
27 
28 // Atomically increment a counter only if the counter value is not zero.
29 // Returns true if increment took place; false if counter is zero.
30 template <typename T>
31 inline bool IncrementIfNonzero(std::atomic<T>* p) {
32  T count = p->load(std::memory_order_acquire);
33  do {
34  // If zero, we are done (without an increment). If not, we must do a CAS
35  // to maintain the contract: do not increment the counter if it is already
36  // zero
37  if (count == 0) {
38  return false;
39  }
40  } while (!p->compare_exchange_weak(
41  count, count + 1, std::memory_order_acq_rel, std::memory_order_acquire));
42  return true;
43 }
44 
45 } // namespace grpc_core
46 
47 #endif /* GRPC_CORE_LIB_GPRPP_ATOMIC_UTILS_H */
grpc_core
Definition: call_metric_recorder.h:31
T
#define T(upbtypeconst, upbtype, ctype, default_value)
count
int * count
Definition: bloaty/third_party/googletest/googlemock/test/gmock_stress_test.cc:96
grpc_core::IncrementIfNonzero
bool IncrementIfNonzero(std::atomic< T > *p)
Definition: atomic_utils.h:31
port_platform.h


grpc
Author(s):
autogenerated on Thu Mar 13 2025 02:58:35