Sub topic 12
Why skip lists suit concurrent access
This chapter assumes you know the skip list operations from the earlier chapters (search, insert and delete with an update array), and that you know what a thread and a lock are.
Updates stay local
A balanced tree keeps its shape with rotations. A rotation changes several nodes near the top of a subtree, and a rebalancing step can propagate up to the root. A thread that rebalances needs exclusive access to a large part of the tree, and every other thread has to wait.
A skip list has no global shape to maintain. Node heights are chosen at random when a node is created, so nothing is rebalanced afterward. An insert changes only the forward pointers of the predecessors recorded in the update array. A delete changes the same predecessors. Two threads working on distant keys touch disjoint nodes and never interfere.
Three levels of locking
- One lock for the whole list. This is correct and simple, but it serializes every operation.
- Per-node locks. An insert locks only its predecessors and checks that they are still linked to the expected successors. This is the idea behind the "lazy" skip list. Searches take no locks. They read pointers and ignore nodes marked as deleted.
- Lock-free. Pointers change with compare-and-swap (CAS), an atomic instruction that writes a new value only if the current value is the expected one. A thread whose CAS fails starts the operation again.
Level 0 is the source of truth
Concurrent designs treat the bottom layer as the real list. Upper layers are only hints for finding a starting point faster. An insert becomes visible at the moment its CAS succeeds on layer 0. The thread then links the upper layers one at a time. A reader that sees a node on layer 0 but not yet on layer 2 still gets a correct answer, because it just walks a few extra steps.
The next example shows the retry pattern on a single layer. Python has no CAS, so a per-node lock simulates one.
import threading
class Node:
__slots__ = ("key", "next", "_lock")
def __init__(self, key, nxt=None):
self.key = key
self.next = nxt
self._lock = threading.Lock()
def cas_next(self, expected, new):
with self._lock:
if self.next is expected:
self.next = new
return True
return False
class SortedList:
def __init__(self):
self.head = Node(None)
def insert(self, key):
while True:
pred = self.head
curr = pred.next
while curr is not None and curr.key < key:
pred, curr = curr, curr.next
if curr is not None and curr.key == key:
return False
if pred.cas_next(curr, Node(key, curr)):
return True
# Another thread changed pred.next first. Search again.
lst = SortedList()
threads = [
threading.Thread(target=lambda s=s: [lst.insert(k) for k in range(s, 2000, 4)])
for s in range(4)
]
for t in threads:
t.start()
for t in threads:
t.join()
keys = []
node = lst.head.next
while node is not None:
keys.append(node.key)
node = node.next
print(keys == list(range(2000))) # TrueThe four threads insert interleaved keys, and every key ends up in the list in order. A thread that loses a race on a shared predecessor retries instead of waiting on a global lock.
Deletion needs two steps
Deleting with a single pointer change is unsafe. Another thread could be inserting a node right after the one being removed, and that insert would be lost. Concurrent skip lists therefore delete in two steps:
- Mark the node as logically deleted, usually by setting a flag in its next pointers.
- Unlink the node physically. Any thread that meets a marked node can finish this step.
Gotchas
- Operations on one key are linearizable, but a range scan over several keys is not an atomic snapshot unless the design adds one.
- The update array can be stale by the time you use it. Always validate the predecessors, or let the CAS fail and retry.
- Unlinked nodes may still be read by other threads. Languages without a garbage collector need hazard pointers or epoch-based reclamation.
- Java's
ConcurrentSkipListMapis a lock-free sorted map. Java has no standard lock-free balanced tree, which is a practical reason this structure was chosen.
Exercise
Why does a skip list insert need to coordinate with fewer threads than a red-black tree insert?
Show answer
An insert changes only the forward pointers of its predecessors, and node heights are random, so no rebalancing step spreads toward the root. A red-black tree insert can recolor and rotate nodes along the path to the root, so it conflicts with more concurrent operations.
Exercise
In the code above, what happens when two threads insert different keys that share the same predecessor?
Show answer
Both find the same pred and curr. One cas_next succeeds. The other fails because pred.next is no longer curr, so that thread loops, searches again from the head, and links its node after the first thread's node or before it, depending on key order.