ConcurrentSkipList.h 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877
  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. //
  18. // A concurrent skip list (CSL) implementation.
  19. // Ref: http://www.cs.tau.ac.il/~shanir/nir-pubs-web/Papers/OPODIS2006-BA.pdf
  20. /*
  21. This implements a sorted associative container that supports only
  22. unique keys. (Similar to std::set.)
  23. Features:
  24. 1. Small memory overhead: ~40% less memory overhead compared with
  25. std::set (1.6 words per node versus 3). It has an minimum of 4
  26. words (7 words if there nodes got deleted) per-list overhead
  27. though.
  28. 2. Read accesses (count, find iterator, skipper) are lock-free and
  29. mostly wait-free (the only wait a reader may need to do is when
  30. the node it is visiting is in a pending stage, i.e. deleting,
  31. adding and not fully linked). Write accesses (remove, add) need
  32. to acquire locks, but locks are local to the predecessor nodes
  33. and/or successor nodes.
  34. 3. Good high contention performance, comparable single-thread
  35. performance. In the multithreaded case (12 workers), CSL tested
  36. 10x faster than a RWSpinLocked std::set for an averaged sized
  37. list (1K - 1M nodes).
  38. Comparable read performance to std::set when single threaded,
  39. especially when the list size is large, and scales better to
  40. larger lists: when the size is small, CSL can be 20-50% slower on
  41. find()/contains(). As the size gets large (> 1M elements),
  42. find()/contains() can be 30% faster.
  43. Iterating through a skiplist is similar to iterating through a
  44. linked list, thus is much (2-6x) faster than on a std::set
  45. (tree-based). This is especially true for short lists due to
  46. better cache locality. Based on that, it's also faster to
  47. intersect two skiplists.
  48. 4. Lazy removal with GC support. The removed nodes get deleted when
  49. the last Accessor to the skiplist is destroyed.
  50. Caveats:
  51. 1. Write operations are usually 30% slower than std::set in a single
  52. threaded environment.
  53. 2. Need to have a head node for each list, which has a 4 word
  54. overhead.
  55. 3. When the list is quite small (< 1000 elements), single threaded
  56. benchmarks show CSL can be 10x slower than std:set.
  57. 4. The interface requires using an Accessor to access the skiplist.
  58. (See below.)
  59. 5. Currently x64 only, due to use of MicroSpinLock.
  60. 6. Freed nodes will not be reclaimed as long as there are ongoing
  61. uses of the list.
  62. Sample usage:
  63. typedef ConcurrentSkipList<int> SkipListT;
  64. shared_ptr<SkipListT> sl(SkipListT::createInstance(init_head_height);
  65. {
  66. // It's usually good practice to hold an accessor only during
  67. // its necessary life cycle (but not in a tight loop as
  68. // Accessor creation incurs ref-counting overhead).
  69. //
  70. // Holding it longer delays garbage-collecting the deleted
  71. // nodes in the list.
  72. SkipListT::Accessor accessor(sl);
  73. accessor.insert(23);
  74. accessor.erase(2);
  75. for (auto &elem : accessor) {
  76. // use elem to access data
  77. }
  78. ... ...
  79. }
  80. Another useful type is the Skipper accessor. This is useful if you
  81. want to skip to locations in the way std::lower_bound() works,
  82. i.e. it can be used for going through the list by skipping to the
  83. node no less than a specified key. The Skipper keeps its location as
  84. state, which makes it convenient for things like implementing
  85. intersection of two sets efficiently, as it can start from the last
  86. visited position.
  87. {
  88. SkipListT::Accessor accessor(sl);
  89. SkipListT::Skipper skipper(accessor);
  90. skipper.to(30);
  91. if (skipper) {
  92. CHECK_LE(30, *skipper);
  93. }
  94. ... ...
  95. // GC may happen when the accessor gets destructed.
  96. }
  97. */
  98. #pragma once
  99. #include <algorithm>
  100. #include <atomic>
  101. #include <limits>
  102. #include <memory>
  103. #include <type_traits>
  104. #include <boost/iterator/iterator_facade.hpp>
  105. #include <glog/logging.h>
  106. #include <folly/ConcurrentSkipList-inl.h>
  107. #include <folly/Likely.h>
  108. #include <folly/Memory.h>
  109. #include <folly/synchronization/MicroSpinLock.h>
  110. namespace folly {
  111. template <
  112. typename T,
  113. typename Comp = std::less<T>,
  114. // All nodes are allocated using provided SysAllocator,
  115. // it should be thread-safe.
  116. typename NodeAlloc = SysAllocator<void>,
  117. int MAX_HEIGHT = 24>
  118. class ConcurrentSkipList {
  119. // MAX_HEIGHT needs to be at least 2 to suppress compiler
  120. // warnings/errors (Werror=uninitialized tiggered due to preds_[1]
  121. // being treated as a scalar in the compiler).
  122. static_assert(
  123. MAX_HEIGHT >= 2 && MAX_HEIGHT < 64,
  124. "MAX_HEIGHT can only be in the range of [2, 64)");
  125. typedef std::unique_lock<folly::MicroSpinLock> ScopedLocker;
  126. typedef ConcurrentSkipList<T, Comp, NodeAlloc, MAX_HEIGHT> SkipListType;
  127. public:
  128. typedef detail::SkipListNode<T> NodeType;
  129. typedef T value_type;
  130. typedef T key_type;
  131. typedef detail::csl_iterator<value_type, NodeType> iterator;
  132. typedef detail::csl_iterator<const value_type, const NodeType> const_iterator;
  133. class Accessor;
  134. class Skipper;
  135. explicit ConcurrentSkipList(int height, const NodeAlloc& alloc)
  136. : recycler_(alloc),
  137. head_(NodeType::create(recycler_.alloc(), height, value_type(), true)),
  138. size_(0) {}
  139. explicit ConcurrentSkipList(int height)
  140. : recycler_(),
  141. head_(NodeType::create(recycler_.alloc(), height, value_type(), true)),
  142. size_(0) {}
  143. // Convenient function to get an Accessor to a new instance.
  144. static Accessor create(int height, const NodeAlloc& alloc) {
  145. return Accessor(createInstance(height, alloc));
  146. }
  147. static Accessor create(int height = 1) {
  148. return Accessor(createInstance(height));
  149. }
  150. // Create a shared_ptr skiplist object with initial head height.
  151. static std::shared_ptr<SkipListType> createInstance(
  152. int height,
  153. const NodeAlloc& alloc) {
  154. return std::make_shared<ConcurrentSkipList>(height, alloc);
  155. }
  156. static std::shared_ptr<SkipListType> createInstance(int height = 1) {
  157. return std::make_shared<ConcurrentSkipList>(height);
  158. }
  159. //===================================================================
  160. // Below are implementation details.
  161. // Please see ConcurrentSkipList::Accessor for stdlib-like APIs.
  162. //===================================================================
  163. ~ConcurrentSkipList() {
  164. if /* constexpr */ (NodeType::template DestroyIsNoOp<NodeAlloc>::value) {
  165. // Avoid traversing the list if using arena allocator.
  166. return;
  167. }
  168. for (NodeType* current = head_.load(std::memory_order_relaxed); current;) {
  169. NodeType* tmp = current->skip(0);
  170. NodeType::destroy(recycler_.alloc(), current);
  171. current = tmp;
  172. }
  173. }
  174. private:
  175. static bool greater(const value_type& data, const NodeType* node) {
  176. return node && Comp()(node->data(), data);
  177. }
  178. static bool less(const value_type& data, const NodeType* node) {
  179. return (node == nullptr) || Comp()(data, node->data());
  180. }
  181. static int findInsertionPoint(
  182. NodeType* cur,
  183. int cur_layer,
  184. const value_type& data,
  185. NodeType* preds[],
  186. NodeType* succs[]) {
  187. int foundLayer = -1;
  188. NodeType* pred = cur;
  189. NodeType* foundNode = nullptr;
  190. for (int layer = cur_layer; layer >= 0; --layer) {
  191. NodeType* node = pred->skip(layer);
  192. while (greater(data, node)) {
  193. pred = node;
  194. node = node->skip(layer);
  195. }
  196. if (foundLayer == -1 && !less(data, node)) { // the two keys equal
  197. foundLayer = layer;
  198. foundNode = node;
  199. }
  200. preds[layer] = pred;
  201. // if found, succs[0..foundLayer] need to point to the cached foundNode,
  202. // as foundNode might be deleted at the same time thus pred->skip() can
  203. // return nullptr or another node.
  204. succs[layer] = foundNode ? foundNode : node;
  205. }
  206. return foundLayer;
  207. }
  208. size_t size() const {
  209. return size_.load(std::memory_order_relaxed);
  210. }
  211. int height() const {
  212. return head_.load(std::memory_order_consume)->height();
  213. }
  214. int maxLayer() const {
  215. return height() - 1;
  216. }
  217. size_t incrementSize(int delta) {
  218. return size_.fetch_add(delta, std::memory_order_relaxed) + delta;
  219. }
  220. // Returns the node if found, nullptr otherwise.
  221. NodeType* find(const value_type& data) {
  222. auto ret = findNode(data);
  223. if (ret.second && !ret.first->markedForRemoval()) {
  224. return ret.first;
  225. }
  226. return nullptr;
  227. }
  228. // lock all the necessary nodes for changing (adding or removing) the list.
  229. // returns true if all the lock acquried successfully and the related nodes
  230. // are all validate (not in certain pending states), false otherwise.
  231. bool lockNodesForChange(
  232. int nodeHeight,
  233. ScopedLocker guards[MAX_HEIGHT],
  234. NodeType* preds[MAX_HEIGHT],
  235. NodeType* succs[MAX_HEIGHT],
  236. bool adding = true) {
  237. NodeType *pred, *succ, *prevPred = nullptr;
  238. bool valid = true;
  239. for (int layer = 0; valid && layer < nodeHeight; ++layer) {
  240. pred = preds[layer];
  241. DCHECK(pred != nullptr) << "layer=" << layer << " height=" << height()
  242. << " nodeheight=" << nodeHeight;
  243. succ = succs[layer];
  244. if (pred != prevPred) {
  245. guards[layer] = pred->acquireGuard();
  246. prevPred = pred;
  247. }
  248. valid = !pred->markedForRemoval() &&
  249. pred->skip(layer) == succ; // check again after locking
  250. if (adding) { // when adding a node, the succ shouldn't be going away
  251. valid = valid && (succ == nullptr || !succ->markedForRemoval());
  252. }
  253. }
  254. return valid;
  255. }
  256. // Returns a paired value:
  257. // pair.first always stores the pointer to the node with the same input key.
  258. // It could be either the newly added data, or the existed data in the
  259. // list with the same key.
  260. // pair.second stores whether the data is added successfully:
  261. // 0 means not added, otherwise reutrns the new size.
  262. template <typename U>
  263. std::pair<NodeType*, size_t> addOrGetData(U&& data) {
  264. NodeType *preds[MAX_HEIGHT], *succs[MAX_HEIGHT];
  265. NodeType* newNode;
  266. size_t newSize;
  267. while (true) {
  268. int max_layer = 0;
  269. int layer = findInsertionPointGetMaxLayer(data, preds, succs, &max_layer);
  270. if (layer >= 0) {
  271. NodeType* nodeFound = succs[layer];
  272. DCHECK(nodeFound != nullptr);
  273. if (nodeFound->markedForRemoval()) {
  274. continue; // if it's getting deleted retry finding node.
  275. }
  276. // wait until fully linked.
  277. while (UNLIKELY(!nodeFound->fullyLinked())) {
  278. }
  279. return std::make_pair(nodeFound, 0);
  280. }
  281. // need to capped at the original height -- the real height may have grown
  282. int nodeHeight =
  283. detail::SkipListRandomHeight::instance()->getHeight(max_layer + 1);
  284. ScopedLocker guards[MAX_HEIGHT];
  285. if (!lockNodesForChange(nodeHeight, guards, preds, succs)) {
  286. continue; // give up the locks and retry until all valid
  287. }
  288. // locks acquired and all valid, need to modify the links under the locks.
  289. newNode = NodeType::create(
  290. recycler_.alloc(), nodeHeight, std::forward<U>(data));
  291. for (int k = 0; k < nodeHeight; ++k) {
  292. newNode->setSkip(k, succs[k]);
  293. preds[k]->setSkip(k, newNode);
  294. }
  295. newNode->setFullyLinked();
  296. newSize = incrementSize(1);
  297. break;
  298. }
  299. int hgt = height();
  300. size_t sizeLimit =
  301. detail::SkipListRandomHeight::instance()->getSizeLimit(hgt);
  302. if (hgt < MAX_HEIGHT && newSize > sizeLimit) {
  303. growHeight(hgt + 1);
  304. }
  305. CHECK_GT(newSize, 0);
  306. return std::make_pair(newNode, newSize);
  307. }
  308. bool remove(const value_type& data) {
  309. NodeType* nodeToDelete = nullptr;
  310. ScopedLocker nodeGuard;
  311. bool isMarked = false;
  312. int nodeHeight = 0;
  313. NodeType *preds[MAX_HEIGHT], *succs[MAX_HEIGHT];
  314. while (true) {
  315. int max_layer = 0;
  316. int layer = findInsertionPointGetMaxLayer(data, preds, succs, &max_layer);
  317. if (!isMarked && (layer < 0 || !okToDelete(succs[layer], layer))) {
  318. return false;
  319. }
  320. if (!isMarked) {
  321. nodeToDelete = succs[layer];
  322. nodeHeight = nodeToDelete->height();
  323. nodeGuard = nodeToDelete->acquireGuard();
  324. if (nodeToDelete->markedForRemoval()) {
  325. return false;
  326. }
  327. nodeToDelete->setMarkedForRemoval();
  328. isMarked = true;
  329. }
  330. // acquire pred locks from bottom layer up
  331. ScopedLocker guards[MAX_HEIGHT];
  332. if (!lockNodesForChange(nodeHeight, guards, preds, succs, false)) {
  333. continue; // this will unlock all the locks
  334. }
  335. for (int k = nodeHeight - 1; k >= 0; --k) {
  336. preds[k]->setSkip(k, nodeToDelete->skip(k));
  337. }
  338. incrementSize(-1);
  339. break;
  340. }
  341. recycle(nodeToDelete);
  342. return true;
  343. }
  344. const value_type* first() const {
  345. auto node = head_.load(std::memory_order_consume)->skip(0);
  346. return node ? &node->data() : nullptr;
  347. }
  348. const value_type* last() const {
  349. NodeType* pred = head_.load(std::memory_order_consume);
  350. NodeType* node = nullptr;
  351. for (int layer = maxLayer(); layer >= 0; --layer) {
  352. do {
  353. node = pred->skip(layer);
  354. if (node) {
  355. pred = node;
  356. }
  357. } while (node != nullptr);
  358. }
  359. return pred == head_.load(std::memory_order_relaxed) ? nullptr
  360. : &pred->data();
  361. }
  362. static bool okToDelete(NodeType* candidate, int layer) {
  363. DCHECK(candidate != nullptr);
  364. return candidate->fullyLinked() && candidate->maxLayer() == layer &&
  365. !candidate->markedForRemoval();
  366. }
  367. // find node for insertion/deleting
  368. int findInsertionPointGetMaxLayer(
  369. const value_type& data,
  370. NodeType* preds[],
  371. NodeType* succs[],
  372. int* max_layer) const {
  373. *max_layer = maxLayer();
  374. return findInsertionPoint(
  375. head_.load(std::memory_order_consume), *max_layer, data, preds, succs);
  376. }
  377. // Find node for access. Returns a paired values:
  378. // pair.first = the first node that no-less than data value
  379. // pair.second = 1 when the data value is founded, or 0 otherwise.
  380. // This is like lower_bound, but not exact: we could have the node marked for
  381. // removal so still need to check that.
  382. std::pair<NodeType*, int> findNode(const value_type& data) const {
  383. return findNodeDownRight(data);
  384. }
  385. // Find node by first stepping down then stepping right. Based on benchmark
  386. // results, this is slightly faster than findNodeRightDown for better
  387. // localality on the skipping pointers.
  388. std::pair<NodeType*, int> findNodeDownRight(const value_type& data) const {
  389. NodeType* pred = head_.load(std::memory_order_consume);
  390. int ht = pred->height();
  391. NodeType* node = nullptr;
  392. bool found = false;
  393. while (!found) {
  394. // stepping down
  395. for (; ht > 0 && less(data, node = pred->skip(ht - 1)); --ht) {
  396. }
  397. if (ht == 0) {
  398. return std::make_pair(node, 0); // not found
  399. }
  400. // node <= data now, but we need to fix up ht
  401. --ht;
  402. // stepping right
  403. while (greater(data, node)) {
  404. pred = node;
  405. node = node->skip(ht);
  406. }
  407. found = !less(data, node);
  408. }
  409. return std::make_pair(node, found);
  410. }
  411. // find node by first stepping right then stepping down.
  412. // We still keep this for reference purposes.
  413. std::pair<NodeType*, int> findNodeRightDown(const value_type& data) const {
  414. NodeType* pred = head_.load(std::memory_order_consume);
  415. NodeType* node = nullptr;
  416. auto top = maxLayer();
  417. int found = 0;
  418. for (int layer = top; !found && layer >= 0; --layer) {
  419. node = pred->skip(layer);
  420. while (greater(data, node)) {
  421. pred = node;
  422. node = node->skip(layer);
  423. }
  424. found = !less(data, node);
  425. }
  426. return std::make_pair(node, found);
  427. }
  428. NodeType* lower_bound(const value_type& data) const {
  429. auto node = findNode(data).first;
  430. while (node != nullptr && node->markedForRemoval()) {
  431. node = node->skip(0);
  432. }
  433. return node;
  434. }
  435. void growHeight(int height) {
  436. NodeType* oldHead = head_.load(std::memory_order_consume);
  437. if (oldHead->height() >= height) { // someone else already did this
  438. return;
  439. }
  440. NodeType* newHead =
  441. NodeType::create(recycler_.alloc(), height, value_type(), true);
  442. { // need to guard the head node in case others are adding/removing
  443. // nodes linked to the head.
  444. ScopedLocker g = oldHead->acquireGuard();
  445. newHead->copyHead(oldHead);
  446. NodeType* expected = oldHead;
  447. if (!head_.compare_exchange_strong(
  448. expected, newHead, std::memory_order_release)) {
  449. // if someone has already done the swap, just return.
  450. NodeType::destroy(recycler_.alloc(), newHead);
  451. return;
  452. }
  453. oldHead->setMarkedForRemoval();
  454. }
  455. recycle(oldHead);
  456. }
  457. void recycle(NodeType* node) {
  458. recycler_.add(node);
  459. }
  460. detail::NodeRecycler<NodeType, NodeAlloc> recycler_;
  461. std::atomic<NodeType*> head_;
  462. std::atomic<size_t> size_;
  463. };
  464. template <typename T, typename Comp, typename NodeAlloc, int MAX_HEIGHT>
  465. class ConcurrentSkipList<T, Comp, NodeAlloc, MAX_HEIGHT>::Accessor {
  466. typedef detail::SkipListNode<T> NodeType;
  467. typedef ConcurrentSkipList<T, Comp, NodeAlloc, MAX_HEIGHT> SkipListType;
  468. public:
  469. typedef T value_type;
  470. typedef T key_type;
  471. typedef T& reference;
  472. typedef T* pointer;
  473. typedef const T& const_reference;
  474. typedef const T* const_pointer;
  475. typedef size_t size_type;
  476. typedef Comp key_compare;
  477. typedef Comp value_compare;
  478. typedef typename SkipListType::iterator iterator;
  479. typedef typename SkipListType::const_iterator const_iterator;
  480. typedef typename SkipListType::Skipper Skipper;
  481. explicit Accessor(std::shared_ptr<ConcurrentSkipList> skip_list)
  482. : slHolder_(std::move(skip_list)) {
  483. sl_ = slHolder_.get();
  484. DCHECK(sl_ != nullptr);
  485. sl_->recycler_.addRef();
  486. }
  487. // Unsafe initializer: the caller assumes the responsibility to keep
  488. // skip_list valid during the whole life cycle of the Acessor.
  489. explicit Accessor(ConcurrentSkipList* skip_list) : sl_(skip_list) {
  490. DCHECK(sl_ != nullptr);
  491. sl_->recycler_.addRef();
  492. }
  493. Accessor(const Accessor& accessor)
  494. : sl_(accessor.sl_), slHolder_(accessor.slHolder_) {
  495. sl_->recycler_.addRef();
  496. }
  497. Accessor& operator=(const Accessor& accessor) {
  498. if (this != &accessor) {
  499. slHolder_ = accessor.slHolder_;
  500. sl_->recycler_.releaseRef();
  501. sl_ = accessor.sl_;
  502. sl_->recycler_.addRef();
  503. }
  504. return *this;
  505. }
  506. ~Accessor() {
  507. sl_->recycler_.releaseRef();
  508. }
  509. bool empty() const {
  510. return sl_->size() == 0;
  511. }
  512. size_t size() const {
  513. return sl_->size();
  514. }
  515. size_type max_size() const {
  516. return std::numeric_limits<size_type>::max();
  517. }
  518. // returns end() if the value is not in the list, otherwise returns an
  519. // iterator pointing to the data, and it's guaranteed that the data is valid
  520. // as far as the Accessor is hold.
  521. iterator find(const key_type& value) {
  522. return iterator(sl_->find(value));
  523. }
  524. const_iterator find(const key_type& value) const {
  525. return iterator(sl_->find(value));
  526. }
  527. size_type count(const key_type& data) const {
  528. return contains(data);
  529. }
  530. iterator begin() const {
  531. NodeType* head = sl_->head_.load(std::memory_order_consume);
  532. return iterator(head->next());
  533. }
  534. iterator end() const {
  535. return iterator(nullptr);
  536. }
  537. const_iterator cbegin() const {
  538. return begin();
  539. }
  540. const_iterator cend() const {
  541. return end();
  542. }
  543. template <
  544. typename U,
  545. typename =
  546. typename std::enable_if<std::is_convertible<U, T>::value>::type>
  547. std::pair<iterator, bool> insert(U&& data) {
  548. auto ret = sl_->addOrGetData(std::forward<U>(data));
  549. return std::make_pair(iterator(ret.first), ret.second);
  550. }
  551. size_t erase(const key_type& data) {
  552. return remove(data);
  553. }
  554. iterator lower_bound(const key_type& data) const {
  555. return iterator(sl_->lower_bound(data));
  556. }
  557. size_t height() const {
  558. return sl_->height();
  559. }
  560. // first() returns pointer to the first element in the skiplist, or
  561. // nullptr if empty.
  562. //
  563. // last() returns the pointer to the last element in the skiplist,
  564. // nullptr if list is empty.
  565. //
  566. // Note: As concurrent writing can happen, first() is not
  567. // guaranteed to be the min_element() in the list. Similarly
  568. // last() is not guaranteed to be the max_element(), and both of them can
  569. // be invalid (i.e. nullptr), so we name them differently from front() and
  570. // tail() here.
  571. const key_type* first() const {
  572. return sl_->first();
  573. }
  574. const key_type* last() const {
  575. return sl_->last();
  576. }
  577. // Try to remove the last element in the skip list.
  578. //
  579. // Returns true if we removed it, false if either the list is empty
  580. // or a race condition happened (i.e. the used-to-be last element
  581. // was already removed by another thread).
  582. bool pop_back() {
  583. auto last = sl_->last();
  584. return last ? sl_->remove(*last) : false;
  585. }
  586. std::pair<key_type*, bool> addOrGetData(const key_type& data) {
  587. auto ret = sl_->addOrGetData(data);
  588. return std::make_pair(&ret.first->data(), ret.second);
  589. }
  590. SkipListType* skiplist() const {
  591. return sl_;
  592. }
  593. // legacy interfaces
  594. // TODO:(xliu) remove these.
  595. // Returns true if the node is added successfully, false if not, i.e. the
  596. // node with the same key already existed in the list.
  597. bool contains(const key_type& data) const {
  598. return sl_->find(data);
  599. }
  600. bool add(const key_type& data) {
  601. return sl_->addOrGetData(data).second;
  602. }
  603. bool remove(const key_type& data) {
  604. return sl_->remove(data);
  605. }
  606. private:
  607. SkipListType* sl_;
  608. std::shared_ptr<SkipListType> slHolder_;
  609. };
  610. // implements forward iterator concept.
  611. template <typename ValT, typename NodeT>
  612. class detail::csl_iterator : public boost::iterator_facade<
  613. csl_iterator<ValT, NodeT>,
  614. ValT,
  615. boost::forward_traversal_tag> {
  616. public:
  617. typedef ValT value_type;
  618. typedef value_type& reference;
  619. typedef value_type* pointer;
  620. typedef ptrdiff_t difference_type;
  621. explicit csl_iterator(NodeT* node = nullptr) : node_(node) {}
  622. template <typename OtherVal, typename OtherNode>
  623. csl_iterator(
  624. const csl_iterator<OtherVal, OtherNode>& other,
  625. typename std::enable_if<
  626. std::is_convertible<OtherVal, ValT>::value>::type* = nullptr)
  627. : node_(other.node_) {}
  628. size_t nodeSize() const {
  629. return node_ == nullptr ? 0
  630. : node_->height() * sizeof(NodeT*) + sizeof(*this);
  631. }
  632. bool good() const {
  633. return node_ != nullptr;
  634. }
  635. private:
  636. friend class boost::iterator_core_access;
  637. template <class, class>
  638. friend class csl_iterator;
  639. void increment() {
  640. node_ = node_->next();
  641. }
  642. bool equal(const csl_iterator& other) const {
  643. return node_ == other.node_;
  644. }
  645. value_type& dereference() const {
  646. return node_->data();
  647. }
  648. NodeT* node_;
  649. };
  650. // Skipper interface
  651. template <typename T, typename Comp, typename NodeAlloc, int MAX_HEIGHT>
  652. class ConcurrentSkipList<T, Comp, NodeAlloc, MAX_HEIGHT>::Skipper {
  653. typedef detail::SkipListNode<T> NodeType;
  654. typedef ConcurrentSkipList<T, Comp, NodeAlloc, MAX_HEIGHT> SkipListType;
  655. typedef typename SkipListType::Accessor Accessor;
  656. public:
  657. typedef T value_type;
  658. typedef T& reference;
  659. typedef T* pointer;
  660. typedef ptrdiff_t difference_type;
  661. Skipper(const std::shared_ptr<SkipListType>& skipList) : accessor_(skipList) {
  662. init();
  663. }
  664. Skipper(const Accessor& accessor) : accessor_(accessor) {
  665. init();
  666. }
  667. void init() {
  668. // need to cache the head node
  669. NodeType* head_node = head();
  670. headHeight_ = head_node->height();
  671. for (int i = 0; i < headHeight_; ++i) {
  672. preds_[i] = head_node;
  673. succs_[i] = head_node->skip(i);
  674. }
  675. int max_layer = maxLayer();
  676. for (int i = 0; i < max_layer; ++i) {
  677. hints_[i] = uint8_t(i + 1);
  678. }
  679. hints_[max_layer] = max_layer;
  680. }
  681. // advance to the next node in the list.
  682. Skipper& operator++() {
  683. preds_[0] = succs_[0];
  684. succs_[0] = preds_[0]->skip(0);
  685. int height = curHeight();
  686. for (int i = 1; i < height && preds_[0] == succs_[i]; ++i) {
  687. preds_[i] = succs_[i];
  688. succs_[i] = preds_[i]->skip(i);
  689. }
  690. return *this;
  691. }
  692. bool good() const {
  693. return succs_[0] != nullptr;
  694. }
  695. int maxLayer() const {
  696. return headHeight_ - 1;
  697. }
  698. int curHeight() const {
  699. // need to cap the height to the cached head height, as the current node
  700. // might be some newly inserted node and also during the time period the
  701. // head height may have grown.
  702. return succs_[0] ? std::min(headHeight_, succs_[0]->height()) : 0;
  703. }
  704. const value_type& data() const {
  705. DCHECK(succs_[0] != nullptr);
  706. return succs_[0]->data();
  707. }
  708. value_type& operator*() const {
  709. DCHECK(succs_[0] != nullptr);
  710. return succs_[0]->data();
  711. }
  712. value_type* operator->() {
  713. DCHECK(succs_[0] != nullptr);
  714. return &succs_[0]->data();
  715. }
  716. /*
  717. * Skip to the position whose data is no less than the parameter.
  718. * (I.e. the lower_bound).
  719. *
  720. * Returns true if the data is found, false otherwise.
  721. */
  722. bool to(const value_type& data) {
  723. int layer = curHeight() - 1;
  724. if (layer < 0) {
  725. return false; // reaches the end of the list
  726. }
  727. int lyr = hints_[layer];
  728. int max_layer = maxLayer();
  729. while (SkipListType::greater(data, succs_[lyr]) && lyr < max_layer) {
  730. ++lyr;
  731. }
  732. hints_[layer] = lyr; // update the hint
  733. int foundLayer = SkipListType::findInsertionPoint(
  734. preds_[lyr], lyr, data, preds_, succs_);
  735. if (foundLayer < 0) {
  736. return false;
  737. }
  738. DCHECK(succs_[0] != nullptr)
  739. << "lyr=" << lyr << "; max_layer=" << max_layer;
  740. return !succs_[0]->markedForRemoval();
  741. }
  742. private:
  743. NodeType* head() const {
  744. return accessor_.skiplist()->head_.load(std::memory_order_consume);
  745. }
  746. Accessor accessor_;
  747. int headHeight_;
  748. NodeType *succs_[MAX_HEIGHT], *preds_[MAX_HEIGHT];
  749. uint8_t hints_[MAX_HEIGHT];
  750. };
  751. } // namespace folly