30/37
Part 6 of 6 · Follow-upsLearn and do

Without a lock, 59 of 100 runs broke, and with one lock none did

Here's a measurement on this lesson's two LRU caches. In each run, 4 threads each made 20,000 random calls on 64 keys, against a cache of capacity 32:

Broken runs out of 100, with 4 threads
linked list, get and put
59
linked list, get only
6
OrderedDict, get and put
1
either, with one lock
0

No lock in the first three. The last holds one threading.Lock inside each method.

What broke:

  • Linked list, get and put: KeyError and AttributeError from half-updated nodes, and lists with too many nodes or one-way links.
  • Linked list, get only: the map and the list disagreed, because nodes fell out of the list.
  • OrderedDict: a KeyError from move_to_end, because another thread evicted the key between two steps.

Thread timing varies from run to run. An earlier run with the same calls and seeds gave 71, 4 and 2 for the unlocked caches, and 0 again with the lock. Here's the code, with the counting left out:

import random
import threading


def hammer(cache, threads=4, ops=20_000, keys=64, seed=0, only_gets=False):
    for key in range(32):
        cache.put(key, key)
    errors = []

    def work(n):
        rng = random.Random(seed * 1000 + n)
        for _ in range(ops):
            key = rng.randrange(keys)
            try:
                if only_gets or rng.random() < 0.5:
                    cache.get(key)
                else:
                    cache.put(key, n)
            except Exception as e:
                errors.append(type(e).__name__)
                if len(errors) > 50:
                    return

    workers = [threading.Thread(target=work, args=(n,)) for n in range(threads)]
    for w in workers:
        w.start()
    for w in workers:
        w.join()
    return errors

A run counts as broken when it raised, or failed the invariant check afterwards: check() on the linked list, and len(cache.data) <= cache.capacity on the OrderedDict. The locked runs wrap each get and put in with self.lock:. Seeds 0 to 99 give the 100 runs.

The get-only number is the one to quote. Even a cache that's only read needs the lock, because in an LRU cache a read is a write.

The OrderedDict broke differently. Its size check held in every run. But if key in data followed by data.move_to_end(key) is two steps, and another thread can evict the key in between.

The fix for both is one lock held for the whole of each public method.

functools.lru_cache handles this for you. Its docs promise that "the underlying data structure will remain coherent during concurrent updates." They also spell out the catch: "It is possible for the wrapped function to be called more than once if another thread makes an additional call before the initial call has been completed and cached."

Predict

One lock around the whole cache becomes the bottleneck. What's the usual next step?

Pick an answer above to see the rest