2 * Copyright 2016 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.
22 #include <folly/detail/Futex.h>
23 #include <folly/Portability.h>
28 * Tiny exclusive lock that packs four lock slots into a single
29 * byte. Each slot is an independent real, sleeping lock. The default
30 * lock and unlock functions operate on slot zero, which modifies only
31 * the low two bits of the host byte.
33 * You should zero-initialize the bits of a MicroLock that you intend
36 * If you're not space-constrained, prefer std::mutex, which will
37 * likely be faster, since it has more than two bits of information to
40 * You are free to put a MicroLock in a union with some other object.
41 * If, for example, you want to use the bottom two bits of a pointer
42 * as a lock, you can put a MicroLock in a union with the pointer and
43 * limit yourself to MicroLock slot zero, which will use the two
44 * least-significant bits in the bottom byte.
46 * (Note that such a union is safe only because MicroLock is based on
47 * a character type, and even under a strict interpretation of C++'s
48 * aliasing rules, character types may alias anything.)
50 * MicroLock uses a dirty trick: it actually operates on the full
51 * word-size, word-aligned bit of memory into which it is embedded.
52 * It never modifies bits outside the ones it's defined to modify, but
53 * it _accesses_ all the bits in the word for purposes of
56 * The MaxSpins template parameter controls the number of times we
57 * spin trying to acquire the lock. MaxYields controls the number of
58 * times we call sched_yield; once we've tried to acquire the lock
59 * MaxSpins + MaxYields times, we sleep on the lock futex.
60 * By adjusting these parameters, you can make MicroLock behave as
61 * much or as little like a conventional spinlock as you'd like.
66 * With the default template options, the timings for uncontended
67 * acquire-then-release come out as follows on Intel(R) Xeon(R) CPU
68 * E5-2660 0 @ 2.20GHz, in @mode/opt, as of the master tree at Tue, 01
71 * ========================================================================
72 * folly/test/SmallLocksBenchmark.cpp relative time/iter iters/s
73 * ========================================================================
74 * MicroSpinLockUncontendedBenchmark 13.46ns 74.28M
75 * PicoSpinLockUncontendedBenchmark 14.99ns 66.71M
76 * MicroLockUncontendedBenchmark 27.06ns 36.96M
77 * StdMutexUncontendedBenchmark 25.18ns 39.72M
78 * VirtualFunctionCall 1.72ns 579.78M
79 * ========================================================================
81 * (The virtual dispatch benchmark is provided for scale.)
83 * The contended case for MicroLock is likely to be worse compared to
84 * std::mutex than the contended case is. Make sure to benchmark your
85 * particular workload.
92 inline detail::Futex<>* word() const;
93 inline uint32_t baseShift(unsigned slot) const;
94 inline uint32_t heldBit(unsigned slot) const;
95 inline uint32_t waitBit(unsigned slot) const;
96 static void lockSlowPath(uint32_t oldWord,
97 detail::Futex<>* wordPtr,
103 inline void unlock(unsigned slot);
104 inline void unlock() { unlock(0); }
105 // Initializes all the slots.
106 inline void init() { lock_ = 0; }
109 inline detail::Futex<>* MicroLockCore::word() const {
110 uintptr_t lockptr = (uintptr_t)&lock_;
111 lockptr &= ~(sizeof(uint32_t) - 1);
112 return (detail::Futex<>*)lockptr;
115 inline unsigned MicroLockCore::baseShift(unsigned slot) const {
116 assert(slot < CHAR_BIT / 2);
118 unsigned offset_bytes = (unsigned)((uintptr_t)&lock_ - (uintptr_t)word());
120 return kIsLittleEndian
121 ? offset_bytes * CHAR_BIT + slot * 2
122 : CHAR_BIT * (sizeof(uint32_t) - offset_bytes - 1) + slot * 2;
125 inline uint32_t MicroLockCore::heldBit(unsigned slot) const {
126 return 1U << (baseShift(slot) + 0);
129 inline uint32_t MicroLockCore::waitBit(unsigned slot) const {
130 return 1U << (baseShift(slot) + 1);
133 void MicroLockCore::unlock(unsigned slot) {
134 detail::Futex<>* wordPtr = word();
138 oldWord = wordPtr->load(std::memory_order_relaxed);
140 assert(oldWord & heldBit(slot));
141 newWord = oldWord & ~(heldBit(slot) | waitBit(slot));
142 } while (!wordPtr->compare_exchange_weak(
143 oldWord, newWord, std::memory_order_release, std::memory_order_relaxed));
145 if (oldWord & waitBit(slot)) {
146 // We don't track the number of waiters, so wake everyone
147 (void)wordPtr->futexWake(std::numeric_limits<int>::max(), heldBit(slot));
151 template <unsigned MaxSpins = 1000, unsigned MaxYields = 0>
152 class MicroLockBase : public MicroLockCore {
154 inline void lock(unsigned slot);
155 inline void lock() { lock(0); }
156 inline bool try_lock(unsigned slot);
157 inline bool try_lock() { return try_lock(0); }
160 template <unsigned MaxSpins, unsigned MaxYields>
161 bool MicroLockBase<MaxSpins, MaxYields>::try_lock(unsigned slot) {
163 // N.B. You might think that try_lock is just the fast path of lock,
164 // but you'd be wrong. Keep in mind that other parts of our host
165 // word might be changing while we take the lock! We're not allowed
166 // to fail spuriously if the lock is in fact not held, even if other
167 // people are concurrently modifying other parts of the word.
169 // We need to loop until we either see firm evidence that somebody
170 // else has the lock (by looking at heldBit) or see our CAS succeed.
171 // A failed CAS by itself does not indicate lock-acquire failure.
173 detail::Futex<>* wordPtr = word();
174 uint32_t oldWord = wordPtr->load(std::memory_order_relaxed);
176 if (oldWord & heldBit(slot)) {
179 } while (!wordPtr->compare_exchange_weak(oldWord,
180 oldWord | heldBit(slot),
181 std::memory_order_acquire,
182 std::memory_order_relaxed));
187 template <unsigned MaxSpins, unsigned MaxYields>
188 void MicroLockBase<MaxSpins, MaxYields>::lock(unsigned slot) {
190 static_assert(MaxSpins + MaxYields < (unsigned)-1, "overflow");
192 detail::Futex<>* wordPtr = word();
194 oldWord = wordPtr->load(std::memory_order_relaxed);
195 if ((oldWord & heldBit(slot)) == 0 &&
196 wordPtr->compare_exchange_weak(oldWord,
197 oldWord | heldBit(slot),
198 std::memory_order_acquire,
199 std::memory_order_relaxed)) {
200 // Fast uncontended case: memory_order_acquire above is our barrier
202 // lockSlowPath doesn't have any slot-dependent computation; it
203 // just shifts the input bit. Make sure its shifting produces the
204 // same result a call to waitBit for our slot would.
205 assert(heldBit(slot) << 1 == waitBit(slot));
206 // lockSlowPath emits its own memory barrier
207 lockSlowPath(oldWord, wordPtr, heldBit(slot), MaxSpins, MaxYields);
211 typedef MicroLockBase<> MicroLock;