ConcurrentSkipList-inl.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. /*
  2. * Copyright 2011-present 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. // @author: Xin Liu <xliux@fb.com>
  17. #pragma once
  18. #include <algorithm>
  19. #include <atomic>
  20. #include <climits>
  21. #include <cmath>
  22. #include <memory>
  23. #include <mutex>
  24. #include <type_traits>
  25. #include <vector>
  26. #include <boost/noncopyable.hpp>
  27. #include <boost/random.hpp>
  28. #include <boost/type_traits.hpp>
  29. #include <glog/logging.h>
  30. #include <folly/Memory.h>
  31. #include <folly/ThreadLocal.h>
  32. #include <folly/synchronization/MicroSpinLock.h>
  33. namespace folly {
  34. namespace detail {
  35. template <typename ValT, typename NodeT>
  36. class csl_iterator;
  37. template <typename T>
  38. class SkipListNode : private boost::noncopyable {
  39. enum : uint16_t {
  40. IS_HEAD_NODE = 1,
  41. MARKED_FOR_REMOVAL = (1 << 1),
  42. FULLY_LINKED = (1 << 2),
  43. };
  44. public:
  45. typedef T value_type;
  46. template <
  47. typename NodeAlloc,
  48. typename U,
  49. typename =
  50. typename std::enable_if<std::is_convertible<U, T>::value>::type>
  51. static SkipListNode*
  52. create(NodeAlloc& alloc, int height, U&& data, bool isHead = false) {
  53. DCHECK(height >= 1 && height < 64) << height;
  54. size_t size =
  55. sizeof(SkipListNode) + height * sizeof(std::atomic<SkipListNode*>);
  56. auto storage = std::allocator_traits<NodeAlloc>::allocate(alloc, size);
  57. // do placement new
  58. return new (storage)
  59. SkipListNode(uint8_t(height), std::forward<U>(data), isHead);
  60. }
  61. template <typename NodeAlloc>
  62. static void destroy(NodeAlloc& alloc, SkipListNode* node) {
  63. size_t size = sizeof(SkipListNode) +
  64. node->height_ * sizeof(std::atomic<SkipListNode*>);
  65. node->~SkipListNode();
  66. std::allocator_traits<NodeAlloc>::deallocate(alloc, node, size);
  67. }
  68. template <typename NodeAlloc>
  69. struct DestroyIsNoOp : StrictConjunction<
  70. AllocatorHasTrivialDeallocate<NodeAlloc>,
  71. boost::has_trivial_destructor<SkipListNode>> {};
  72. // copy the head node to a new head node assuming lock acquired
  73. SkipListNode* copyHead(SkipListNode* node) {
  74. DCHECK(node != nullptr && height_ > node->height_);
  75. setFlags(node->getFlags());
  76. for (uint8_t i = 0; i < node->height_; ++i) {
  77. setSkip(i, node->skip(i));
  78. }
  79. return this;
  80. }
  81. inline SkipListNode* skip(int layer) const {
  82. DCHECK_LT(layer, height_);
  83. return skip_[layer].load(std::memory_order_consume);
  84. }
  85. // next valid node as in the linked list
  86. SkipListNode* next() {
  87. SkipListNode* node;
  88. for (node = skip(0); (node != nullptr && node->markedForRemoval());
  89. node = node->skip(0)) {
  90. }
  91. return node;
  92. }
  93. void setSkip(uint8_t h, SkipListNode* next) {
  94. DCHECK_LT(h, height_);
  95. skip_[h].store(next, std::memory_order_release);
  96. }
  97. value_type& data() {
  98. return data_;
  99. }
  100. const value_type& data() const {
  101. return data_;
  102. }
  103. int maxLayer() const {
  104. return height_ - 1;
  105. }
  106. int height() const {
  107. return height_;
  108. }
  109. std::unique_lock<MicroSpinLock> acquireGuard() {
  110. return std::unique_lock<MicroSpinLock>(spinLock_);
  111. }
  112. bool fullyLinked() const {
  113. return getFlags() & FULLY_LINKED;
  114. }
  115. bool markedForRemoval() const {
  116. return getFlags() & MARKED_FOR_REMOVAL;
  117. }
  118. bool isHeadNode() const {
  119. return getFlags() & IS_HEAD_NODE;
  120. }
  121. void setIsHeadNode() {
  122. setFlags(uint16_t(getFlags() | IS_HEAD_NODE));
  123. }
  124. void setFullyLinked() {
  125. setFlags(uint16_t(getFlags() | FULLY_LINKED));
  126. }
  127. void setMarkedForRemoval() {
  128. setFlags(uint16_t(getFlags() | MARKED_FOR_REMOVAL));
  129. }
  130. private:
  131. // Note! this can only be called from create() as a placement new.
  132. template <typename U>
  133. SkipListNode(uint8_t height, U&& data, bool isHead)
  134. : height_(height), data_(std::forward<U>(data)) {
  135. spinLock_.init();
  136. setFlags(0);
  137. if (isHead) {
  138. setIsHeadNode();
  139. }
  140. // need to explicitly init the dynamic atomic pointer array
  141. for (uint8_t i = 0; i < height_; ++i) {
  142. new (&skip_[i]) std::atomic<SkipListNode*>(nullptr);
  143. }
  144. }
  145. ~SkipListNode() {
  146. for (uint8_t i = 0; i < height_; ++i) {
  147. skip_[i].~atomic();
  148. }
  149. }
  150. uint16_t getFlags() const {
  151. return flags_.load(std::memory_order_consume);
  152. }
  153. void setFlags(uint16_t flags) {
  154. flags_.store(flags, std::memory_order_release);
  155. }
  156. // TODO(xliu): on x86_64, it's possible to squeeze these into
  157. // skip_[0] to maybe save 8 bytes depending on the data alignments.
  158. // NOTE: currently this is x86_64 only anyway, due to the
  159. // MicroSpinLock.
  160. std::atomic<uint16_t> flags_;
  161. const uint8_t height_;
  162. MicroSpinLock spinLock_;
  163. value_type data_;
  164. std::atomic<SkipListNode*> skip_[0];
  165. };
  166. class SkipListRandomHeight {
  167. enum { kMaxHeight = 64 };
  168. public:
  169. // make it a singleton.
  170. static SkipListRandomHeight* instance() {
  171. static SkipListRandomHeight instance_;
  172. return &instance_;
  173. }
  174. int getHeight(int maxHeight) const {
  175. DCHECK_LE(maxHeight, kMaxHeight) << "max height too big!";
  176. double p = randomProb();
  177. for (int i = 0; i < maxHeight; ++i) {
  178. if (p < lookupTable_[i]) {
  179. return i + 1;
  180. }
  181. }
  182. return maxHeight;
  183. }
  184. size_t getSizeLimit(int height) const {
  185. DCHECK_LT(height, kMaxHeight);
  186. return sizeLimitTable_[height];
  187. }
  188. private:
  189. SkipListRandomHeight() {
  190. initLookupTable();
  191. }
  192. void initLookupTable() {
  193. // set skip prob = 1/E
  194. static const double kProbInv = exp(1);
  195. static const double kProb = 1.0 / kProbInv;
  196. static const size_t kMaxSizeLimit = std::numeric_limits<size_t>::max();
  197. double sizeLimit = 1;
  198. double p = lookupTable_[0] = (1 - kProb);
  199. sizeLimitTable_[0] = 1;
  200. for (int i = 1; i < kMaxHeight - 1; ++i) {
  201. p *= kProb;
  202. sizeLimit *= kProbInv;
  203. lookupTable_[i] = lookupTable_[i - 1] + p;
  204. sizeLimitTable_[i] = sizeLimit > kMaxSizeLimit
  205. ? kMaxSizeLimit
  206. : static_cast<size_t>(sizeLimit);
  207. }
  208. lookupTable_[kMaxHeight - 1] = 1;
  209. sizeLimitTable_[kMaxHeight - 1] = kMaxSizeLimit;
  210. }
  211. static double randomProb() {
  212. static ThreadLocal<boost::lagged_fibonacci2281> rng_;
  213. return (*rng_)();
  214. }
  215. double lookupTable_[kMaxHeight];
  216. size_t sizeLimitTable_[kMaxHeight];
  217. };
  218. template <typename NodeType, typename NodeAlloc, typename = void>
  219. class NodeRecycler;
  220. template <typename NodeType, typename NodeAlloc>
  221. class NodeRecycler<
  222. NodeType,
  223. NodeAlloc,
  224. typename std::enable_if<
  225. !NodeType::template DestroyIsNoOp<NodeAlloc>::value>::type> {
  226. public:
  227. explicit NodeRecycler(const NodeAlloc& alloc)
  228. : refs_(0), dirty_(false), alloc_(alloc) {
  229. lock_.init();
  230. }
  231. explicit NodeRecycler() : refs_(0), dirty_(false) {
  232. lock_.init();
  233. }
  234. ~NodeRecycler() {
  235. CHECK_EQ(refs(), 0);
  236. if (nodes_) {
  237. for (auto& node : *nodes_) {
  238. NodeType::destroy(alloc_, node);
  239. }
  240. }
  241. }
  242. void add(NodeType* node) {
  243. std::lock_guard<MicroSpinLock> g(lock_);
  244. if (nodes_.get() == nullptr) {
  245. nodes_ = std::make_unique<std::vector<NodeType*>>(1, node);
  246. } else {
  247. nodes_->push_back(node);
  248. }
  249. DCHECK_GT(refs(), 0);
  250. dirty_.store(true, std::memory_order_relaxed);
  251. }
  252. int addRef() {
  253. return refs_.fetch_add(1, std::memory_order_relaxed);
  254. }
  255. int releaseRef() {
  256. // We don't expect to clean the recycler immediately everytime it is OK
  257. // to do so. Here, it is possible that multiple accessors all release at
  258. // the same time but nobody would clean the recycler here. If this
  259. // happens, the recycler will usually still get cleaned when
  260. // such a race doesn't happen. The worst case is the recycler will
  261. // eventually get deleted along with the skiplist.
  262. if (LIKELY(!dirty_.load(std::memory_order_relaxed) || refs() > 1)) {
  263. return refs_.fetch_add(-1, std::memory_order_relaxed);
  264. }
  265. std::unique_ptr<std::vector<NodeType*>> newNodes;
  266. {
  267. std::lock_guard<MicroSpinLock> g(lock_);
  268. if (nodes_.get() == nullptr || refs() > 1) {
  269. return refs_.fetch_add(-1, std::memory_order_relaxed);
  270. }
  271. // once refs_ reaches 1 and there is no other accessor, it is safe to
  272. // remove all the current nodes in the recycler, as we already acquired
  273. // the lock here so no more new nodes can be added, even though new
  274. // accessors may be added after that.
  275. newNodes.swap(nodes_);
  276. dirty_.store(false, std::memory_order_relaxed);
  277. }
  278. // TODO(xliu) should we spawn a thread to do this when there are large
  279. // number of nodes in the recycler?
  280. for (auto& node : *newNodes) {
  281. NodeType::destroy(alloc_, node);
  282. }
  283. // decrease the ref count at the very end, to minimize the
  284. // chance of other threads acquiring lock_ to clear the deleted
  285. // nodes again.
  286. return refs_.fetch_add(-1, std::memory_order_relaxed);
  287. }
  288. NodeAlloc& alloc() {
  289. return alloc_;
  290. }
  291. private:
  292. int refs() const {
  293. return refs_.load(std::memory_order_relaxed);
  294. }
  295. std::unique_ptr<std::vector<NodeType*>> nodes_;
  296. std::atomic<int32_t> refs_; // current number of visitors to the list
  297. std::atomic<bool> dirty_; // whether *nodes_ is non-empty
  298. MicroSpinLock lock_; // protects access to *nodes_
  299. NodeAlloc alloc_;
  300. };
  301. // In case of arena allocator, no recycling is necessary, and it's possible
  302. // to save on ConcurrentSkipList size.
  303. template <typename NodeType, typename NodeAlloc>
  304. class NodeRecycler<
  305. NodeType,
  306. NodeAlloc,
  307. typename std::enable_if<
  308. NodeType::template DestroyIsNoOp<NodeAlloc>::value>::type> {
  309. public:
  310. explicit NodeRecycler(const NodeAlloc& alloc) : alloc_(alloc) {}
  311. void addRef() {}
  312. void releaseRef() {}
  313. void add(NodeType* /* node */) {}
  314. NodeAlloc& alloc() {
  315. return alloc_;
  316. }
  317. private:
  318. NodeAlloc alloc_;
  319. };
  320. } // namespace detail
  321. } // namespace folly