Pylerno
English

Threads, shared state, and locks

Two workers each reserve one item. Only one item is available. Decide exactly which operations must be indivisible. Run this example locally.

On this page

Read the model

Threads in one process share the same inventory object. Reading the count, testing it, and writing a new count are separate steps. A lock protects the decision only if every participant follows the same locking rule. A process pool, in contrast, normally gives workers separate Python object state. Coordinating one stock count across processes requires shared storage or explicit communication.

Follow the example

python
from concurrent.futures import ThreadPoolExecutor
from threading import Lock

class Inventory:
    def __init__(self):
        self.remaining = 1
        self.lock = Lock()

    def reserve(self):
        with self.lock:
            if self.remaining == 0:
                return False
            self.remaining -= 1
            return True

stock = Inventory()
with ThreadPoolExecutor(max_workers=2) as pool:
    requests = [pool.submit(stock.reserve) for _ in range(2)]
print(sum(job.result() for job in requests), stock.remaining)

Both calls receive the same Inventory object. The first worker inside the lock sees one item and takes it. The next sees zero. Which worker wins can vary, but the printed totals are always 1 and 0. Leaving the with block releases the lock even on return.

Change one condition

Move the zero check above the with block. Two workers could both pass the check before either decrements the stock. Draw that order on paper. Repeating the test many times cannot prove that the race is absent. The repaired version keeps checking and decrementing in the same critical section.

Python reference.

Check your understanding

Stock is one. Which pair must share the lock to prevent two successful reservations?

Choose one answer

Search documentation

Share this page