GCC Code Coverage Report


Directory: cvmfs/
File: cvmfs/fence.h
Date: 2026-10-11 02:40:02
Exec Total Coverage
Lines: 23 25 92.0%
Branches: 2 4 50.0%

Line Branch Exec Source
1 /**
2 * This file is part of the CernVM File System.
3 */
4
5 #ifndef CVMFS_FENCE_H_
6 #define CVMFS_FENCE_H_
7
8 #include <atomic>
9
10 #include "duplex_testing.h"
11 #include "util/posix.h"
12 #include "util/single_copy.h"
13
14 #ifdef CVMFS_NAMESPACE_GUARD
15 namespace CVMFS_NAMESPACE_GUARD {
16 #endif
17
18 /**
19 * A Fence can be used to protect critical regions where blocking is a very
20 * rare operation. When the Fence is not blocked, entering and leaving a
21 * critical region requires only a 1-2 atomic operations. In order to block
22 * the fence, no new threads can enter a critical region. When all entered
23 * regions are left, the fence is blocked. Waiting is done through slow busy
24 * wait.
25 */
26 class Fence : public SingleCopy {
27 FRIEND_TEST(T_Fence, Basics);
28
29 public:
30 43 Fence() {
31 43 counter_.store(0);
32 43 blocking_.store(0);
33 43 }
34
35 86 void Enter() {
36
1/2
✗ Branch 1 not taken.
✓ Branch 2 taken 86 times.
172 while (blocking_.load()) {
37 ✗ SafeSleepMs(kBusyWaitBackoffMs);
38 }
39 86 counter_.fetch_add(1);
40 86 }
41
42 86 void Leave() { counter_.fetch_sub(1); }
43
44 86 void Close() {
45 86 int32_t expected_val = 0;
46 86 blocking_.compare_exchange_strong(expected_val, 1);
47 86 }
48
49 /**
50 * Close and let live critical regions exit
51 */
52 43 void Drain() {
53 43 Close();
54
1/2
✗ Branch 1 not taken.
✓ Branch 2 taken 43 times.
86 while (counter_.load() > 0) {
55 ✗ SafeSleepMs(kBusyWaitBackoffMs);
56 }
57 43 }
58
59 86 void Open() {
60 86 int32_t expected_val = 1;
61 86 blocking_.compare_exchange_strong(expected_val, 0);
62 86 }
63
64 private:
65 static const unsigned kBusyWaitBackoffMs = 100;
66
67 /**
68 * Number of active critical regions.
69 */
70 std::atomic<int64_t> counter_;
71
72 /**
73 * A boolean that indicates if the fence is blocked.
74 */
75 std::atomic<int32_t> blocking_;
76 };
77
78
79 /**
80 * RAII wrapper in case an entire function or code block should be protected
81 * by a fence.
82 */
83 class FenceGuard {
84 public:
85 43 explicit FenceGuard(Fence *fence) : fence_(fence) { fence_->Enter(); }
86 43 ~FenceGuard() { fence_->Leave(); }
87
88 private:
89 Fence *fence_;
90 };
91
92 #ifdef CVMFS_NAMESPACE_GUARD
93 } // namespace CVMFS_NAMESPACE_GUARD
94 #endif
95
96 #endif // CVMFS_FENCE_H_
97