2 * Copyright 2011-present Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * Higher performance (up to 10x) atomic increment using thread caching.
20 * @author Spencer Ahrens (sahrens)
27 #include <boost/noncopyable.hpp>
29 #include <folly/Likely.h>
30 #include <folly/ThreadLocal.h>
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
39 template <class IntT, class Tag=IntT>
40 class ThreadCachedInt : boost::noncopyable {
44 explicit ThreadCachedInt(IntT initialVal = 0, uint32_t cacheSize = 1000)
45 : target_(initialVal), cacheSize_(cacheSize) {
48 void increment(IntT inc) {
49 auto cache = cache_.get();
50 if (UNLIKELY(cache == nullptr)) {
51 cache = new IntCache(*this);
54 cache->increment(inc);
57 // Quickly grabs the current value which may not include some cached
59 IntT readFast() const {
60 return target_.load(std::memory_order_relaxed);
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);
78 // Quickly reads and resets current value (doesn't reset cached increments).
79 IntT readFastAndReset() {
80 return target_.exchange(0, std::memory_order_release);
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);
101 void setCacheSize(uint32_t newSize) {
102 cacheSize_.store(newSize, std::memory_order_release);
105 uint32_t getCacheSize() const {
106 return cacheSize_.load();
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--() {
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);
125 target_.store(newVal, std::memory_order_release);
129 std::atomic<IntT> target_;
130 std::atomic<uint32_t> cacheSize_;
131 ThreadLocalPtr<IntCache, Tag, AccessModeStrict>
132 cache_; // Must be last for dtor ordering
134 // This should only ever be modified by one thread
136 ThreadCachedInt* parent_;
137 mutable std::atomic<IntT> val_;
138 mutable uint32_t numUpdates_;
139 std::atomic<bool> reset_;
141 explicit IntCache(ThreadCachedInt& parent)
142 : parent_(&parent), val_(0), numUpdates_(0), reset_(false) {}
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.
149 val_.load(std::memory_order_relaxed) + inc,
150 std::memory_order_release
153 val_.store(inc, std::memory_order_relaxed);
154 reset_.store(false, std::memory_order_release);
157 if (UNLIKELY(numUpdates_ >
158 parent_->cacheSize_.load(std::memory_order_acquire))) {
164 parent_->target_.fetch_add(val_, std::memory_order_release);
165 val_.store(0, std::memory_order_release);