2 * Copyright 2017 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 * N.B. You most likely do _not_ want to use MicroSpinLock or any
19 * other kind of spinlock. Consider MicroLock instead.
21 * In short, spinlocks in preemptive multi-tasking operating systems
22 * have serious problems and fast mutexes like std::mutex are almost
23 * certainly the better choice, because letting the OS scheduler put a
24 * thread to sleep is better for system responsiveness and throughput
25 * than wasting a timeslice repeatedly querying a lock held by a
26 * thread that's blocked, and you can't prevent userspace
29 * Spinlocks in an operating system kernel make much more sense than
30 * they do in userspace.
36 * @author Keith Adams <kma@fb.com>
37 * @author Jordan DeLong <delong.j@fb.com>
42 #include <type_traits>
43 #include <boost/noncopyable.hpp>
48 #include <glog/logging.h>
49 #include <folly/detail/Sleeper.h>
50 #include <folly/Portability.h>
55 * A really, *really* small spinlock for fine-grained locking of lots
58 * Zero initializing these is guaranteed to be as good as calling
59 * init(), since the free state is guaranteed to be all-bits zero.
61 * This class should be kept a POD, so we can used it in other packed
62 * structs (gcc does not allow __attribute__((__packed__)) on structs that
63 * contain non-POD data). This means avoid adding a constructor, or
64 * making some members private, etc.
66 struct MicroSpinLock {
67 enum { FREE = 0, LOCKED = 1 };
68 // lock_ can't be std::atomic<> to preserve POD-ness.
71 // Initialize this MSL. It is unnecessary to call this if you
72 // zero-initialize the MicroSpinLock.
74 payload()->store(FREE);
78 return cas(FREE, LOCKED);
82 detail::Sleeper sleeper;
84 while (payload()->load() != FREE) {
87 } while (!try_lock());
88 DCHECK(payload()->load() == LOCKED);
92 CHECK(payload()->load() == LOCKED);
93 payload()->store(FREE, std::memory_order_release);
97 std::atomic<uint8_t>* payload() {
98 return reinterpret_cast<std::atomic<uint8_t>*>(&this->lock_);
101 bool cas(uint8_t compare, uint8_t newVal) {
102 return std::atomic_compare_exchange_strong_explicit(payload(), &compare, newVal,
103 std::memory_order_acquire,
104 std::memory_order_relaxed);
108 std::is_pod<MicroSpinLock>::value,
109 "MicroSpinLock must be kept a POD type.");
111 //////////////////////////////////////////////////////////////////////
114 * Array of spinlocks where each one is padded to prevent false sharing.
115 * Useful for shard-based locking implementations in environments where
116 * contention is unlikely.
119 // TODO: generate it from configure (`getconf LEVEL1_DCACHE_LINESIZE`)
120 #define FOLLY_CACHE_LINE_SIZE 64
122 template <class T, size_t N>
123 struct FOLLY_ALIGNED_MAX SpinLockArray {
124 T& operator[](size_t i) {
125 return data_[i].lock;
128 const T& operator[](size_t i) const {
129 return data_[i].lock;
132 constexpr size_t size() const { return N; }
135 struct PaddedSpinLock {
136 PaddedSpinLock() : lock() {}
138 char padding[FOLLY_CACHE_LINE_SIZE - sizeof(T)];
140 static_assert(sizeof(PaddedSpinLock) == FOLLY_CACHE_LINE_SIZE,
141 "Invalid size of PaddedSpinLock");
143 // Check if T can theoretically cross a cache line.
144 static_assert(alignof(std::max_align_t) > 0 &&
145 FOLLY_CACHE_LINE_SIZE % alignof(std::max_align_t) == 0 &&
146 sizeof(T) <= alignof(std::max_align_t),
147 "T can cross cache line boundaries");
149 char padding_[FOLLY_CACHE_LINE_SIZE];
150 std::array<PaddedSpinLock, N> data_;
153 //////////////////////////////////////////////////////////////////////
155 typedef std::lock_guard<MicroSpinLock> MSLGuard;
157 //////////////////////////////////////////////////////////////////////