作者: 谢瑞阳 10225101483 徐翔宇 10225101535
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

378 linhas
11 KiB

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