Split get_default() into two for deferred default construction
[folly.git] / folly / ThreadCachedInt.h
1 /*
2  * Copyright 2017 Facebook, Inc.
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 /**
18  * Higher performance (up to 10x) atomic increment using thread caching.
19  *
20  * @author Spencer Ahrens (sahrens)
21  */
22
23 #pragma once
24
25 #include <atomic>
26
27 #include <boost/noncopyable.hpp>
28
29 #include <folly/Likely.h>
30 #include <folly/ThreadLocal.h>
31
32 namespace folly {
33
34
35 // Note that readFull requires holding a lock and iterating through all of the
36 // thread local objects with the same Tag, so if you have a lot of
37 // ThreadCachedInt's you should considering breaking up the Tag space even
38 // further.
39 template <class IntT, class Tag=IntT>
40 class ThreadCachedInt : boost::noncopyable {
41   struct IntCache;
42
43  public:
44   explicit ThreadCachedInt(IntT initialVal = 0, uint32_t cacheSize = 1000)
45     : target_(initialVal), cacheSize_(cacheSize) {
46   }
47
48   void increment(IntT inc) {
49     auto cache = cache_.get();
50     if (UNLIKELY(cache == nullptr)) {
51       cache = new IntCache(*this);
52       cache_.reset(cache);
53     }
54     cache->increment(inc);
55   }
56
57   // Quickly grabs the current value which may not include some cached
58   // increments.
59   IntT readFast() const {
60     return target_.load(std::memory_order_relaxed);
61   }
62
63   // Reads the current value plus all the cached increments.  Requires grabbing
64   // a lock, so this is significantly slower than readFast().
65   IntT readFull() const {
66     // This could race with thread destruction and so the access lock should be
67     // acquired before reading the current value
68     auto accessor = cache_.accessAllThreads();
69     IntT ret = readFast();
70     for (const auto& cache : accessor) {
71       if (!cache.reset_.load(std::memory_order_acquire)) {
72         ret += cache.val_.load(std::memory_order_relaxed);
73       }
74     }
75     return ret;
76   }
77
78   // Quickly reads and resets current value (doesn't reset cached increments).
79   IntT readFastAndReset() {
80     return target_.exchange(0, std::memory_order_release);
81   }
82
83   // This function is designed for accumulating into another counter, where you
84   // only want to count each increment once.  It can still get the count a
85   // little off, however, but it should be much better than calling readFull()
86   // and set(0) sequentially.
87   IntT readFullAndReset() {
88     // This could race with thread destruction and so the access lock should be
89     // acquired before reading the current value
90     auto accessor = cache_.accessAllThreads();
91     IntT ret = readFastAndReset();
92     for (auto& cache : accessor) {
93       if (!cache.reset_.load(std::memory_order_acquire)) {
94         ret += cache.val_.load(std::memory_order_relaxed);
95         cache.reset_.store(true, std::memory_order_release);
96       }
97     }
98     return ret;
99   }
100
101   void setCacheSize(uint32_t newSize) {
102     cacheSize_.store(newSize, std::memory_order_release);
103   }
104
105   uint32_t getCacheSize() const {
106     return cacheSize_.load();
107   }
108
109   ThreadCachedInt& operator+=(IntT inc) { increment(inc); return *this; }
110   ThreadCachedInt& operator-=(IntT inc) { increment(-inc); return *this; }
111   // pre-increment (we don't support post-increment)
112   ThreadCachedInt& operator++() { increment(1); return *this; }
113   ThreadCachedInt& operator--() {
114     increment(IntT(-1));
115     return *this;
116   }
117
118   // Thread-safe set function.
119   // This is a best effort implementation. In some edge cases, there could be
120   // data loss (missing counts)
121   void set(IntT newVal) {
122     for (auto& cache : cache_.accessAllThreads()) {
123       cache.reset_.store(true, std::memory_order_release);
124     }
125     target_.store(newVal, std::memory_order_release);
126   }
127
128  private:
129   std::atomic<IntT> target_;
130   std::atomic<uint32_t> cacheSize_;
131   ThreadLocalPtr<IntCache, Tag, AccessModeStrict>
132       cache_; // Must be last for dtor ordering
133
134   // This should only ever be modified by one thread
135   struct IntCache {
136     ThreadCachedInt* parent_;
137     mutable std::atomic<IntT> val_;
138     mutable uint32_t numUpdates_;
139     std::atomic<bool> reset_;
140
141     explicit IntCache(ThreadCachedInt& parent)
142         : parent_(&parent), val_(0), numUpdates_(0), reset_(false) {}
143
144     void increment(IntT inc) {
145       if (LIKELY(!reset_.load(std::memory_order_acquire))) {
146         // This thread is the only writer to val_, so it's fine do do
147         // a relaxed load and do the addition non-atomically.
148         val_.store(
149           val_.load(std::memory_order_relaxed) + inc,
150           std::memory_order_release
151         );
152       } else {
153         val_.store(inc, std::memory_order_relaxed);
154         reset_.store(false, std::memory_order_release);
155       }
156       ++numUpdates_;
157       if (UNLIKELY(numUpdates_ >
158                    parent_->cacheSize_.load(std::memory_order_acquire))) {
159         flush();
160       }
161     }
162
163     void flush() const {
164       parent_->target_.fetch_add(val_, std::memory_order_release);
165       val_.store(0, std::memory_order_release);
166       numUpdates_ = 0;
167     }
168
169     ~IntCache() {
170       flush();
171     }
172   };
173 };
174
175 } // namespace folly