YugabyteDB (2.13.0.0-b42, bfc6a6643e7399ac8a0e81d06a3ee6d6571b33ab)

Coverage Report

Created: 2022-03-09 17:30

/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
144k
      : timeout_(timeout) {}
30
31
235k
  void Store(const T& value) {
32
235k
    time_.store(CoarseTimePoint::min(), std::memory_order_release);
33
235k
    value_ = value;
34
235k
    time_.store(CoarseMonoClock::now(), std::memory_order_release);
35
235k
  }
36
37
20.1M
  T Load() const {
38
20.1M
    for (;;) {
39
20.1M
      auto time1 = time_.load(std::memory_order_acquire);
40
20.1M
      ANNOTATE_IGNORE_READS_BEGIN();
41
20.1M
      auto result = value_;
42
20.1M
      ANNOTATE_IGNORE_READS_END();
43
20.1M
      auto time2 = time_.load(std::memory_order_acquire);
44
20.1M
      if (time1 == time2 && time1 != CoarseTimePoint::min()) {
45
20.1M
        if (CoarseMonoClock::now() - time1 > timeout_) {
46
473k
          return T();
47
473k
        }
48
19.6M
        return result;
49
19.6M
      }
50
20.1M
    }
51
20.1M
  }
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