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>
45 #include <type_traits>
47 #include <folly/Portability.h>
48 #include <folly/detail/Sleeper.h>
53 * A really, *really* small spinlock for fine-grained locking of lots
56 * Zero initializing these is guaranteed to be as good as calling
57 * init(), since the free state is guaranteed to be all-bits zero.
59 * This class should be kept a POD, so we can used it in other packed
60 * structs (gcc does not allow __attribute__((__packed__)) on structs that
61 * contain non-POD data). This means avoid adding a constructor, or
62 * making some members private, etc.
64 struct MicroSpinLock {
65 enum { FREE = 0, LOCKED = 1 };
66 // lock_ can't be std::atomic<> to preserve POD-ness.
69 // Initialize this MSL. It is unnecessary to call this if you
70 // zero-initialize the MicroSpinLock.
72 payload()->store(FREE);
76 return cas(FREE, LOCKED);
80 detail::Sleeper sleeper;
82 while (payload()->load() != FREE) {
85 } while (!try_lock());
86 assert(payload()->load() == LOCKED);
90 assert(payload()->load() == LOCKED);
91 payload()->store(FREE, std::memory_order_release);
95 std::atomic<uint8_t>* payload() {
96 return reinterpret_cast<std::atomic<uint8_t>*>(&this->lock_);
99 bool cas(uint8_t compare, uint8_t newVal) {
100 return std::atomic_compare_exchange_strong_explicit(payload(), &compare, newVal,
101 std::memory_order_acquire,
102 std::memory_order_relaxed);
106 std::is_pod<MicroSpinLock>::value,
107 "MicroSpinLock must be kept a POD type.");
109 //////////////////////////////////////////////////////////////////////
112 * Array of spinlocks where each one is padded to prevent false sharing.
113 * Useful for shard-based locking implementations in environments where
114 * contention is unlikely.
117 // TODO: generate it from configure (`getconf LEVEL1_DCACHE_LINESIZE`)
118 #define FOLLY_CACHE_LINE_SIZE 64
120 template <class T, size_t N>
121 struct FOLLY_ALIGNED_MAX SpinLockArray {
122 T& operator[](size_t i) {
123 return data_[i].lock;
126 const T& operator[](size_t i) const {
127 return data_[i].lock;
130 constexpr size_t size() const { return N; }
133 struct PaddedSpinLock {
134 PaddedSpinLock() : lock() {}
136 char padding[FOLLY_CACHE_LINE_SIZE - sizeof(T)];
138 static_assert(sizeof(PaddedSpinLock) == FOLLY_CACHE_LINE_SIZE,
139 "Invalid size of PaddedSpinLock");
141 // Check if T can theoretically cross a cache line.
143 folly::max_align_v > 0 &&
144 FOLLY_CACHE_LINE_SIZE % folly::max_align_v == 0 &&
145 sizeof(T) <= folly::max_align_v,
146 "T can cross cache line boundaries");
148 char padding_[FOLLY_CACHE_LINE_SIZE];
149 std::array<PaddedSpinLock, N> data_;
152 //////////////////////////////////////////////////////////////////////
154 typedef std::lock_guard<MicroSpinLock> MSLGuard;
156 //////////////////////////////////////////////////////////////////////