29/37
Part 6 of 6 · Follow-upsLearn and do
What interviewers ask next
Make it thread-safe: in an LRU cache, a read is a write
Two threads calling get and put at once can interleave their pointer changes. And get writes too: every hit moves a node. Here is one order of steps that loses a node, with two gets and no put at all:
The list holds a, b, c. Thread 1 runs get("a"), thread 2 get("b"). Both unlink their node. Then both read tail.prev before either one pushes back:
Both threads read tail.prev as c, then each pushes its node after c, thread 1 first. How does the list end?
Pick an answer above to see the rest