skiplist.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file. See the AUTHORS file for names of contributors.
  4. #ifndef STORAGE_LEVELDB_DB_SKIPLIST_H_
  5. #define STORAGE_LEVELDB_DB_SKIPLIST_H_
  6. // Thread safety
  7. // -------------
  8. //
  9. // Writes require external synchronization, most likely a mutex.
  10. // Reads require a guarantee that the SkipList will not be destroyed
  11. // while the read is in progress. Apart from that, reads progress
  12. // without any internal locking or synchronization.
  13. //
  14. // Invariants:
  15. //
  16. // (1) Allocated nodes are never deleted until the SkipList is
  17. // destroyed. This is trivially guaranteed by the code since we
  18. // never delete any skip list nodes.
  19. //
  20. // (2) The contents of a Node except for the next/prev pointers are
  21. // immutable after the Node has been linked into the SkipList.
  22. // Only Insert() modifies the list, and it is careful to initialize
  23. // a node and use release-stores to publish the nodes in one or
  24. // more lists.
  25. //
  26. // ... prev vs. next pointer ordering ...
  27. #include <atomic>
  28. #include <cassert>
  29. #include <cstdlib>
  30. #include "util/arena.h"
  31. #include "util/random.h"
  32. namespace leveldb {
  33. class Arena;
  34. template<typename Key, class Comparator>
  35. class SkipList {
  36. private:
  37. struct Node;
  38. public:
  39. // Create a new SkipList object that will use "cmp" for comparing keys,
  40. // and will allocate memory using "*arena". Objects allocated in the arena
  41. // must remain allocated for the lifetime of the skiplist object.
  42. explicit SkipList(Comparator cmp, Arena* arena);
  43. // Insert key into the list.
  44. // REQUIRES: nothing that compares equal to key is currently in the list.
  45. void Insert(const Key& key);
  46. // Returns true iff an entry that compares equal to key is in the list.
  47. bool Contains(const Key& key) const;
  48. // Iteration over the contents of a skip list
  49. class Iterator {
  50. public:
  51. // Initialize an iterator over the specified list.
  52. // The returned iterator is not valid.
  53. explicit Iterator(const SkipList* list);
  54. // Returns true iff the iterator is positioned at a valid node.
  55. bool Valid() const;
  56. // Returns the key at the current position.
  57. // REQUIRES: Valid()
  58. const Key& key() const;
  59. // Advances to the next position.
  60. // REQUIRES: Valid()
  61. void Next();
  62. // Advances to the previous position.
  63. // REQUIRES: Valid()
  64. void Prev();
  65. // Advance to the first entry with a key >= target
  66. void Seek(const Key& target);
  67. // Position at the first entry in list.
  68. // Final state of iterator is Valid() iff list is not empty.
  69. void SeekToFirst();
  70. // Position at the last entry in list.
  71. // Final state of iterator is Valid() iff list is not empty.
  72. void SeekToLast();
  73. private:
  74. const SkipList* list_;
  75. Node* node_;
  76. // Intentionally copyable
  77. };
  78. private:
  79. enum { kMaxHeight = 12 };
  80. // Immutable after construction
  81. Comparator const compare_;
  82. Arena* const arena_; // Arena used for allocations of nodes
  83. Node* const head_;
  84. // Modified only by Insert(). Read racily by readers, but stale
  85. // values are ok.
  86. std::atomic<int> max_height_; // Height of the entire list
  87. inline int GetMaxHeight() const {
  88. return max_height_.load(std::memory_order_relaxed);
  89. }
  90. // Read/written only by Insert().
  91. Random rnd_;
  92. Node* NewNode(const Key& key, int height);
  93. int RandomHeight();
  94. bool Equal(const Key& a, const Key& b) const { return (compare_(a, b) == 0); }
  95. // Return true if key is greater than the data stored in "n"
  96. bool KeyIsAfterNode(const Key& key, Node* n) const;
  97. // Return the earliest node that comes at or after key.
  98. // Return nullptr if there is no such node.
  99. //
  100. // If prev is non-null, fills prev[level] with pointer to previous
  101. // node at "level" for every level in [0..max_height_-1].
  102. Node* FindGreaterOrEqual(const Key& key, Node** prev) const;
  103. // Return the latest node with a key < key.
  104. // Return head_ if there is no such node.
  105. Node* FindLessThan(const Key& key) const;
  106. // Return the last node in the list.
  107. // Return head_ if list is empty.
  108. Node* FindLast() const;
  109. // No copying allowed
  110. SkipList(const SkipList&);
  111. void operator=(const SkipList&);
  112. };
  113. // Implementation details follow
  114. template<typename Key, class Comparator>
  115. struct SkipList<Key, Comparator>::Node {
  116. explicit Node(const Key& k) : key(k) { }
  117. Key const key;
  118. // Accessors/mutators for links. Wrapped in methods so we can
  119. // add the appropriate barriers as necessary.
  120. Node* Next(int n) {
  121. assert(n >= 0);
  122. // Use an 'acquire load' so that we observe a fully initialized
  123. // version of the returned Node.
  124. return next_[n].load(std::memory_order_acquire);
  125. }
  126. void SetNext(int n, Node* x) {
  127. assert(n >= 0);
  128. // Use a 'release store' so that anybody who reads through this
  129. // pointer observes a fully initialized version of the inserted node.
  130. next_[n].store(x, std::memory_order_release);
  131. }
  132. // No-barrier variants that can be safely used in a few locations.
  133. Node* NoBarrier_Next(int n) {
  134. assert(n >= 0);
  135. return next_[n].load(std::memory_order_relaxed);
  136. }
  137. void NoBarrier_SetNext(int n, Node* x) {
  138. assert(n >= 0);
  139. next_[n].store(x, std::memory_order_relaxed);
  140. }
  141. private:
  142. // Array of length equal to the node height. next_[0] is lowest level link.
  143. std::atomic<Node*> next_[1];
  144. };
  145. template<typename Key, class Comparator>
  146. typename SkipList<Key, Comparator>::Node*
  147. SkipList<Key, Comparator>::NewNode(const Key& key, int height) {
  148. char* const node_memory = arena_->AllocateAligned(
  149. sizeof(Node) + sizeof(std::atomic<Node*>) * (height - 1));
  150. return new (node_memory) Node(key);
  151. }
  152. template<typename Key, class Comparator>
  153. inline SkipList<Key, Comparator>::Iterator::Iterator(const SkipList* list) {
  154. list_ = list;
  155. node_ = nullptr;
  156. }
  157. template<typename Key, class Comparator>
  158. inline bool SkipList<Key, Comparator>::Iterator::Valid() const {
  159. return node_ != nullptr;
  160. }
  161. template<typename Key, class Comparator>
  162. inline const Key& SkipList<Key, Comparator>::Iterator::key() const {
  163. assert(Valid());
  164. return node_->key;
  165. }
  166. template<typename Key, class Comparator>
  167. inline void SkipList<Key, Comparator>::Iterator::Next() {
  168. assert(Valid());
  169. node_ = node_->Next(0);
  170. }
  171. template<typename Key, class Comparator>
  172. inline void SkipList<Key, Comparator>::Iterator::Prev() {
  173. // Instead of using explicit "prev" links, we just search for the
  174. // last node that falls before key.
  175. assert(Valid());
  176. node_ = list_->FindLessThan(node_->key);
  177. if (node_ == list_->head_) {
  178. node_ = nullptr;
  179. }
  180. }
  181. template<typename Key, class Comparator>
  182. inline void SkipList<Key, Comparator>::Iterator::Seek(const Key& target) {
  183. node_ = list_->FindGreaterOrEqual(target, nullptr);
  184. }
  185. template<typename Key, class Comparator>
  186. inline void SkipList<Key, Comparator>::Iterator::SeekToFirst() {
  187. node_ = list_->head_->Next(0);
  188. }
  189. template<typename Key, class Comparator>
  190. inline void SkipList<Key, Comparator>::Iterator::SeekToLast() {
  191. node_ = list_->FindLast();
  192. if (node_ == list_->head_) {
  193. node_ = nullptr;
  194. }
  195. }
  196. template<typename Key, class Comparator>
  197. int SkipList<Key, Comparator>::RandomHeight() {
  198. // Increase height with probability 1 in kBranching
  199. static const unsigned int kBranching = 4;
  200. int height = 1;
  201. while (height < kMaxHeight && ((rnd_.Next() % kBranching) == 0)) {
  202. height++;
  203. }
  204. assert(height > 0);
  205. assert(height <= kMaxHeight);
  206. return height;
  207. }
  208. template<typename Key, class Comparator>
  209. bool SkipList<Key, Comparator>::KeyIsAfterNode(const Key& key, Node* n) const {
  210. // null n is considered infinite
  211. return (n != nullptr) && (compare_(n->key, key) < 0);
  212. }
  213. template<typename Key, class Comparator>
  214. typename SkipList<Key, Comparator>::Node*
  215. SkipList<Key, Comparator>::FindGreaterOrEqual(const Key& key,
  216. Node** prev) const {
  217. Node* x = head_;
  218. int level = GetMaxHeight() - 1;
  219. while (true) {
  220. Node* next = x->Next(level);
  221. if (KeyIsAfterNode(key, next)) {
  222. // Keep searching in this list
  223. x = next;
  224. } else {
  225. if (prev != nullptr) prev[level] = x;
  226. if (level == 0) {
  227. return next;
  228. } else {
  229. // Switch to next list
  230. level--;
  231. }
  232. }
  233. }
  234. }
  235. template<typename Key, class Comparator>
  236. typename SkipList<Key, Comparator>::Node*
  237. SkipList<Key, Comparator>::FindLessThan(const Key& key) const {
  238. Node* x = head_;
  239. int level = GetMaxHeight() - 1;
  240. while (true) {
  241. assert(x == head_ || compare_(x->key, key) < 0);
  242. Node* next = x->Next(level);
  243. if (next == nullptr || compare_(next->key, key) >= 0) {
  244. if (level == 0) {
  245. return x;
  246. } else {
  247. // Switch to next list
  248. level--;
  249. }
  250. } else {
  251. x = next;
  252. }
  253. }
  254. }
  255. template<typename Key, class Comparator>
  256. typename SkipList<Key, Comparator>::Node* SkipList<Key, Comparator>::FindLast()
  257. const {
  258. Node* x = head_;
  259. int level = GetMaxHeight() - 1;
  260. while (true) {
  261. Node* next = x->Next(level);
  262. if (next == nullptr) {
  263. if (level == 0) {
  264. return x;
  265. } else {
  266. // Switch to next list
  267. level--;
  268. }
  269. } else {
  270. x = next;
  271. }
  272. }
  273. }
  274. template<typename Key, class Comparator>
  275. SkipList<Key, Comparator>::SkipList(Comparator cmp, Arena* arena)
  276. : compare_(cmp),
  277. arena_(arena),
  278. head_(NewNode(0 /* any key will do */, kMaxHeight)),
  279. max_height_(1),
  280. rnd_(0xdeadbeef) {
  281. for (int i = 0; i < kMaxHeight; i++) {
  282. head_->SetNext(i, nullptr);
  283. }
  284. }
  285. template<typename Key, class Comparator>
  286. void SkipList<Key, Comparator>::Insert(const Key& key) {
  287. // TODO(opt): We can use a barrier-free variant of FindGreaterOrEqual()
  288. // here since Insert() is externally synchronized.
  289. Node* prev[kMaxHeight];
  290. Node* x = FindGreaterOrEqual(key, prev);
  291. // Our data structure does not allow duplicate insertion
  292. assert(x == nullptr || !Equal(key, x->key));
  293. int height = RandomHeight();
  294. if (height > GetMaxHeight()) {
  295. for (int i = GetMaxHeight(); i < height; i++) {
  296. prev[i] = head_;
  297. }
  298. // It is ok to mutate max_height_ without any synchronization
  299. // with concurrent readers. A concurrent reader that observes
  300. // the new value of max_height_ will see either the old value of
  301. // new level pointers from head_ (nullptr), or a new value set in
  302. // the loop below. In the former case the reader will
  303. // immediately drop to the next level since nullptr sorts after all
  304. // keys. In the latter case the reader will use the new node.
  305. max_height_.store(height, std::memory_order_relaxed);
  306. }
  307. x = NewNode(key, height);
  308. for (int i = 0; i < height; i++) {
  309. // NoBarrier_SetNext() suffices since we will add a barrier when
  310. // we publish a pointer to "x" in prev[i].
  311. x->NoBarrier_SetNext(i, prev[i]->NoBarrier_Next(i));
  312. prev[i]->SetNext(i, x);
  313. }
  314. }
  315. template<typename Key, class Comparator>
  316. bool SkipList<Key, Comparator>::Contains(const Key& key) const {
  317. Node* x = FindGreaterOrEqual(key, nullptr);
  318. if (x != nullptr && Equal(key, x->key)) {
  319. return true;
  320. } else {
  321. return false;
  322. }
  323. }
  324. } // namespace leveldb
  325. #endif // STORAGE_LEVELDB_DB_SKIPLIST_H_