xref: /aosp_15_r20/external/federated-compute/fcp/base/reentrancy_guard.h (revision 14675a029014e728ec732f129a32e299b2da0601)
1 /*
2  * Copyright 2021 Google LLC
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef FCP_BASE_REENTRANCY_GUARD_H_
18 #define FCP_BASE_REENTRANCY_GUARD_H_
19 
20 #include <atomic>
21 
22 #include "fcp/base/monitoring.h"
23 
24 namespace fcp {
25 
26 /**
27  * ReentrancyGuard class is used to enforce strictly sequential calling pattern.
28  * Usage pattern:
29  *
30  * Status Method(...) {
31  *   ReentrancyGuard guard;
32  *   FCP_RETURN_IF_ERROR(guard.Check(&in_use_));
33  *
34  *   // The rest of the method body...
35  * }
36  *
37  * in_use_ above is std::atomic<bool> value stored in the object which methods
38  * are enforced.
39  */
40 class ReentrancyGuard {
41  public:
Check(std::atomic<bool> * in_use)42   Status Check(std::atomic<bool>* in_use) {
43     FCP_CHECK(in_use != nullptr);
44     bool expected_value = false;
45     if (!in_use->compare_exchange_strong(expected_value, true)) {
46       return FCP_STATUS(FAILED_PRECONDITION)
47              << "Concurrent method calls detected";
48     }
49 
50     in_use_ = in_use;
51     return FCP_STATUS(OK);
52   }
53 
~ReentrancyGuard()54   ~ReentrancyGuard() {
55     if (in_use_ != nullptr) {
56       in_use_->store(false);
57     }
58   }
59 
60  private:
61   // Pointer to atomic boolean value which is owned by the object which methods
62   // are guarded against reentrancy. This value is set to true when inside
63   // a method call; otherwise false.
64   // Note: std::atomic is used here rather than Mutex is emphasise non-blocking
65   // nature of the implementation. The purpose in_use_ is only to check against
66   // reentrancy rather than synchronization.
67   std::atomic<bool>* in_use_ = nullptr;
68 };
69 
70 }  // namespace fcp
71 
72 #endif  // FCP_BASE_REENTRANCY_GUARD_H_
73