/Users/deen/code/yugabyte-db/src/yb/util/concurrent_pod.h
Line | Count | Source |
1 | | // Copyright (c) YugaByte, Inc. |
2 | | // |
3 | | // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except |
4 | | // in compliance with the License. You may obtain a copy of the License at |
5 | | // |
6 | | // http://www.apache.org/licenses/LICENSE-2.0 |
7 | | // |
8 | | // Unless required by applicable law or agreed to in writing, software distributed under the License |
9 | | // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express |
10 | | // or implied. See the License for the specific language governing permissions and limitations |
11 | | // under the License. |
12 | | // |
13 | | |
14 | | #ifndef YB_UTIL_CONCURRENT_POD_H |
15 | | #define YB_UTIL_CONCURRENT_POD_H |
16 | | |
17 | | #include "yb/gutil/dynamic_annotations.h" |
18 | | #include "yb/util/monotime.h" |
19 | | |
20 | | namespace yb { |
21 | | |
22 | | // Concurrent wrapper for POD objects that does not fit into std::atomic. |
23 | | // Designed for frequent reads with rare writes. |
24 | | // Usual cost of read is 2 atomic load + copy of value. |
25 | | template <class T> |
26 | | class ConcurrentPod { |
27 | | public: |
28 | | explicit ConcurrentPod(const std::chrono::steady_clock::duration& timeout) |
29 | 212k | : timeout_(timeout) {} |
30 | | |
31 | 2.25M | void Store(const T& value) { |
32 | 2.25M | time_.store(CoarseTimePoint::min(), std::memory_order_release); |
33 | 2.25M | value_ = value; |
34 | 2.25M | time_.store(CoarseMonoClock::now(), std::memory_order_release); |
35 | 2.25M | } |
36 | | |
37 | 77.8M | T Load() const { |
38 | 79.6M | for (;;) { |
39 | 79.6M | auto time1 = time_.load(std::memory_order_acquire); |
40 | 79.6M | ANNOTATE_IGNORE_READS_BEGIN(); |
41 | 79.6M | auto result = value_; |
42 | 79.6M | ANNOTATE_IGNORE_READS_END(); |
43 | 79.6M | auto time2 = time_.load(std::memory_order_acquire); |
44 | 79.6M | if (time1 == time2 && time1 != CoarseTimePoint::min()79.4M ) { |
45 | 77.8M | if (CoarseMonoClock::now() - time1 > timeout_) { |
46 | 4.50M | return T(); |
47 | 4.50M | } |
48 | 73.2M | return result; |
49 | 77.8M | } |
50 | 79.6M | } |
51 | 77.8M | } |
52 | | private: |
53 | | const std::chrono::steady_clock::duration timeout_; |
54 | | T value_; |
55 | | std::atomic<CoarseTimePoint> time_{CoarseTimePoint()}; |
56 | | }; |
57 | | |
58 | | } // namespace yb |
59 | | |
60 | | #endif // YB_UTIL_CONCURRENT_POD_H |