]> git.proxmox.com Git - ceph.git/blob - ceph/src/common/item_history.h
update sources to ceph Nautilus 14.2.1
[ceph.git] / ceph / src / common / item_history.h
1 // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
2 // vim: ts=8 sw=2 smarttab
3
4 #pragma once
5
6 #include <list>
7 #include <mutex>
8
9 /*
10
11 Keep a history of item values so that readers can dereference the pointer to
12 the latest value and continue using it as long as they want. This container
13 is only appropriate for values that are updated a handful of times over their
14 total lifetime.
15
16 There is a prune() method to throw out old values, but it should only be used
17 if the caller has some way of knowing all readers are done.
18
19 */
20
21 template<class T>
22 class mutable_item_history {
23 private:
24 std::mutex lock;
25 std::list<T> history;
26 T *current = nullptr;
27
28 public:
29 mutable_item_history() {
30 history.emplace_back(T());
31 current = &history.back();
32 }
33
34 // readers are lock-free
35 const T& operator*() const {
36 return *current;
37 }
38 const T *operator->() const {
39 return current;
40 }
41
42 // non-const variants (be careful!)
43 T& operator*() {
44 return *current;
45 }
46 T *operator->() {
47 return current;
48 }
49
50 // writes are serialized
51 const T& operator=(const T& other) {
52 std::lock_guard l(lock);
53 history.push_back(other);
54 current = &history.back();
55 return *current;
56 }
57
58 void prune() {
59 // note: this is not necessarily thread-safe wrt readers
60 std::lock_guard l(lock);
61 while (history.size() > 1) {
62 history.pop_front();
63 }
64 }
65 };
66
67 template<class T>
68 class safe_item_history {
69 private:
70 std::mutex lock;
71 std::list<T> history;
72 T *current = nullptr;
73
74 public:
75 safe_item_history() {
76 history.emplace_back(T());
77 current = &history.back();
78 }
79
80 // readers are lock-free
81 const T& operator*() const {
82 return *current;
83 }
84 const T *operator->() const {
85 return current;
86 }
87
88 // writes are serialized
89 const T& operator=(const T& other) {
90 std::lock_guard l(lock);
91 history.push_back(other);
92 current = &history.back();
93 return *current;
94 }
95
96 void prune() {
97 // note: this is not necessarily thread-safe wrt readers
98 std::lock_guard l(lock);
99 while (history.size() > 1) {
100 history.pop_front();
101 }
102 }
103 };