Skip to content
LLD Learn/Concurrency for LLD
Browsing as a guest. Sign in to save your progress and earn XP as you complete chapters.

Locks, Thread-Safe Singletons & Producer-Consumer

6 min read

You'll learn to

  • -Explain, in plain words, what a thread, a race condition and a lock are
  • -Fix the parking-lot race with a lock and see the difference in a run
  • -Choose between coarse-grained and fine-grained locks and name the deadlock risk
  • -Explain when a read-write lock helps and how a bounded blocking queue coordinates producers and consumers

A thread is one stream of work inside a running program. A program can run many threads at once, and they all share the same memory. That sharing is what makes them useful and what makes them dangerous. The previous chapter showed the danger: two cars, each on its own thread, both check that one parking spot is free and both take it. This chapter is about the tools that stop that, starting with the lock.

An Analogy: A One-Stall Bathroom

A bathroom with one stall has a lock on the door. Whoever is inside slides the lock across, and everyone else waits in a line outside. Nobody ever walks in on someone else, and the line moves as people leave. A lock in code is that door lock.

  • -A person is a thread.
  • -The stall is the critical section: the few lines of code that must never run in two threads at once.
  • -The door lock is the lock object, acquired on the way in and released on the way out.
  • -The queue outside is the set of threads waiting for the lock.

Fixing the Parking Lot With a Lock

The bug is a check-then-act sequence: look at the counter, then change it. If a second thread runs between the look and the change, both act on stale information. The fix is to make the check and the act one critical section. Run the code below. The sleep inside park() forces the unlucky interleaving so that you can see it every time.

Two cars, one spot: the same code with and without a lock

Without the lock both threads see one free spot and both park, so two cars were told yes and the counter ends at -1. With the lock, the second thread waits at the door, then sees zero spots and is told no. The word with does the acquiring and releasing for you, and it releases the lock even if the code inside raises an error.

Coarse-Grained or Fine-Grained?

One lock around the whole lot is coarse-grained. It is simple and definitely correct, but every car queues behind every other car, even cars heading for different floors. A fine-grained design uses one lock per floor, so cars on different floors do not wait for each other. The price is complexity, and a new danger: deadlock.

A deadlock happens when two threads each hold one lock and wait for the other's. Picture two people at a narrow doorway, each holding one chopstick and waiting for the other to put theirs down. Neither ever does. In code it looks like this:

Opposite lock order: each thread waits forever for the lock the other one holds
lock_a, lock_b = threading.Lock(), threading.Lock()

def transfer_one():          # thread 1
    with lock_a:
        with lock_b: ...     # waits for lock_b while holding lock_a

def transfer_two():          # thread 2
    with lock_b:
        with lock_a: ...     # waits for lock_a while holding lock_b

The usual cure is a rule that every thread takes locks in the same order, for example always lock_a before lock_b. The practical interview advice is to start coarse-grained, and to move to fine-grained locking only when you can state a concrete contention reason, such as thousands of requests per second spread over many floors.

Read-Write Locks: Many Readers or One Writer

Think of a noticeboard in a corridor. Any number of people can read it at the same moment without getting in each other's way, but when someone needs to rewrite it, everyone must step away first. A read-write lock works the same way: any number of readers at once, or exactly one writer, never both. It pays off when reads vastly outnumber writes, such as checking the free-spot count a hundred times for every assignment. Python's standard library has no built-in version, so in an interview you describe the idea.

Producer and Consumer: The Kitchen Shelf

In a restaurant the cooks put plates on a shelf and the waiters take them off. The shelf holds only a few plates. If it is full, the cooks must wait. If it is empty, the waiters must wait. A bounded blocking queue is that shelf. Producers add items, consumers remove them, and the queue makes the right side wait instead of spinning in a loop or dropping data. Read the code in order, then run it.

A bounded blocking queue: one cook thread, one waiter thread, a shelf of two
  • -wait() lets a thread sleep until it is told something changed, and it releases the lock while it sleeps, so others can make progress.
  • -notify() wakes one waiting thread after the state changes: a producer wakes a consumer, and a consumer wakes a producer.
  • -The while loop around wait() is deliberate. A woken thread re-checks the condition, because another thread may have got there first.

Whatever the timing, the plates come out in order and the shelf never holds more than two. In real code you would usually use queue.Queue(maxsize=n) from the standard library, which does exactly this. The same shape sits behind thread pools, message queues and rate limiters with a burst allowance.

The thread-safe Singleton from the creational patterns module is another small example of using a lock only where needed: it locks the narrow moment when the instance does not exist yet, and skips the lock on every later call.

Interview Signal is part of Pro

See a real weak answer next to a real strong one for this exact topic.

Quiz is part of Pro

Test what you just read with a short quiz, and bank the XP.

Discussion0

Join the Discussion

Sign in to leave comments, reply to others, or like insights.

Sign In to ScaleDojo

No comments yet. Be the first to start the thread!