logging: reduce the amount of code emitted for log statements
[folly.git] / folly / MicroSpinLock.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  * N.B. You most likely do _not_ want to use MicroSpinLock or any
19  * other kind of spinlock.  Consider MicroLock instead.
20  *
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
27  * programs blocking.
28  *
29  * Spinlocks in an operating system kernel make much more sense than
30  * they do in userspace.
31  */
32
33 #pragma once
34
35 /*
36  * @author Keith Adams <kma@fb.com>
37  * @author Jordan DeLong <delong.j@fb.com>
38  */
39
40 #include <array>
41 #include <cinttypes>
42 #include <type_traits>
43 #include <boost/noncopyable.hpp>
44 #include <cstdlib>
45 #include <mutex>
46 #include <atomic>
47
48 #include <glog/logging.h>
49 #include <folly/detail/Sleeper.h>
50 #include <folly/Portability.h>
51
52 namespace folly {
53
54 /*
55  * A really, *really* small spinlock for fine-grained locking of lots
56  * of teeny-tiny data.
57  *
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.
60  *
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.
65  */
66 struct MicroSpinLock {
67   enum { FREE = 0, LOCKED = 1 };
68   // lock_ can't be std::atomic<> to preserve POD-ness.
69   uint8_t lock_;
70
71   // Initialize this MSL.  It is unnecessary to call this if you
72   // zero-initialize the MicroSpinLock.
73   void init() {
74     payload()->store(FREE);
75   }
76
77   bool try_lock() {
78     return cas(FREE, LOCKED);
79   }
80
81   void lock() {
82     detail::Sleeper sleeper;
83     do {
84       while (payload()->load() != FREE) {
85         sleeper.wait();
86       }
87     } while (!try_lock());
88     DCHECK(payload()->load() == LOCKED);
89   }
90
91   void unlock() {
92     CHECK(payload()->load() == LOCKED);
93     payload()->store(FREE, std::memory_order_release);
94   }
95
96  private:
97   std::atomic<uint8_t>* payload() {
98     return reinterpret_cast<std::atomic<uint8_t>*>(&this->lock_);
99   }
100
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);
105   }
106 };
107 static_assert(
108     std::is_pod<MicroSpinLock>::value,
109     "MicroSpinLock must be kept a POD type.");
110
111 //////////////////////////////////////////////////////////////////////
112
113 /**
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.
117  */
118
119 // TODO: generate it from configure (`getconf LEVEL1_DCACHE_LINESIZE`)
120 #define FOLLY_CACHE_LINE_SIZE 64
121
122 template <class T, size_t N>
123 struct FOLLY_ALIGNED_MAX SpinLockArray {
124   T& operator[](size_t i) {
125     return data_[i].lock;
126   }
127
128   const T& operator[](size_t i) const {
129     return data_[i].lock;
130   }
131
132   constexpr size_t size() const { return N; }
133
134  private:
135   struct PaddedSpinLock {
136     PaddedSpinLock() : lock() {}
137     T lock;
138     char padding[FOLLY_CACHE_LINE_SIZE - sizeof(T)];
139   };
140   static_assert(sizeof(PaddedSpinLock) == FOLLY_CACHE_LINE_SIZE,
141                 "Invalid size of PaddedSpinLock");
142
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");
148
149   char padding_[FOLLY_CACHE_LINE_SIZE];
150   std::array<PaddedSpinLock, N> data_;
151 };
152
153 //////////////////////////////////////////////////////////////////////
154
155 typedef std::lock_guard<MicroSpinLock> MSLGuard;
156
157 //////////////////////////////////////////////////////////////////////
158
159 }