Explicitly initialize AsyncSocket in MockAsyncSSLSocket
[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 <atomic>
42 #include <cinttypes>
43 #include <cstdlib>
44 #include <mutex>
45 #include <type_traits>
46
47 #include <boost/noncopyable.hpp>
48 #include <glog/logging.h>
49
50 #include <folly/Portability.h>
51 #include <folly/detail/Sleeper.h>
52
53 namespace folly {
54
55 /*
56  * A really, *really* small spinlock for fine-grained locking of lots
57  * of teeny-tiny data.
58  *
59  * Zero initializing these is guaranteed to be as good as calling
60  * init(), since the free state is guaranteed to be all-bits zero.
61  *
62  * This class should be kept a POD, so we can used it in other packed
63  * structs (gcc does not allow __attribute__((__packed__)) on structs that
64  * contain non-POD data).  This means avoid adding a constructor, or
65  * making some members private, etc.
66  */
67 struct MicroSpinLock {
68   enum { FREE = 0, LOCKED = 1 };
69   // lock_ can't be std::atomic<> to preserve POD-ness.
70   uint8_t lock_;
71
72   // Initialize this MSL.  It is unnecessary to call this if you
73   // zero-initialize the MicroSpinLock.
74   void init() {
75     payload()->store(FREE);
76   }
77
78   bool try_lock() {
79     return cas(FREE, LOCKED);
80   }
81
82   void lock() {
83     detail::Sleeper sleeper;
84     do {
85       while (payload()->load() != FREE) {
86         sleeper.wait();
87       }
88     } while (!try_lock());
89     DCHECK(payload()->load() == LOCKED);
90   }
91
92   void unlock() {
93     CHECK(payload()->load() == LOCKED);
94     payload()->store(FREE, std::memory_order_release);
95   }
96
97  private:
98   std::atomic<uint8_t>* payload() {
99     return reinterpret_cast<std::atomic<uint8_t>*>(&this->lock_);
100   }
101
102   bool cas(uint8_t compare, uint8_t newVal) {
103     return std::atomic_compare_exchange_strong_explicit(payload(), &compare, newVal,
104                                                         std::memory_order_acquire,
105                                                         std::memory_order_relaxed);
106   }
107 };
108 static_assert(
109     std::is_pod<MicroSpinLock>::value,
110     "MicroSpinLock must be kept a POD type.");
111
112 //////////////////////////////////////////////////////////////////////
113
114 /**
115  * Array of spinlocks where each one is padded to prevent false sharing.
116  * Useful for shard-based locking implementations in environments where
117  * contention is unlikely.
118  */
119
120 // TODO: generate it from configure (`getconf LEVEL1_DCACHE_LINESIZE`)
121 #define FOLLY_CACHE_LINE_SIZE 64
122
123 template <class T, size_t N>
124 struct FOLLY_ALIGNED_MAX SpinLockArray {
125   T& operator[](size_t i) {
126     return data_[i].lock;
127   }
128
129   const T& operator[](size_t i) const {
130     return data_[i].lock;
131   }
132
133   constexpr size_t size() const { return N; }
134
135  private:
136   struct PaddedSpinLock {
137     PaddedSpinLock() : lock() {}
138     T lock;
139     char padding[FOLLY_CACHE_LINE_SIZE - sizeof(T)];
140   };
141   static_assert(sizeof(PaddedSpinLock) == FOLLY_CACHE_LINE_SIZE,
142                 "Invalid size of PaddedSpinLock");
143
144   // Check if T can theoretically cross a cache line.
145   static_assert(
146       folly::max_align_v > 0 &&
147           FOLLY_CACHE_LINE_SIZE % folly::max_align_v == 0 &&
148           sizeof(T) <= folly::max_align_v,
149       "T can cross cache line boundaries");
150
151   char padding_[FOLLY_CACHE_LINE_SIZE];
152   std::array<PaddedSpinLock, N> data_;
153 };
154
155 //////////////////////////////////////////////////////////////////////
156
157 typedef std::lock_guard<MicroSpinLock> MSLGuard;
158
159 //////////////////////////////////////////////////////////////////////
160
161 }