0Pricing
Python Academy · Lesson

Sharing Data Safely

Use queues and locks.

The Race Condition Problem

When multiple threads modify the same data, their operations can interleave and corrupt the result. This is a race condition. We need synchronization tools to share data safely.

import threading

counter = 0

def bump():
    global counter
    for _ in range(100000):
        counter += 1

ts = [threading.Thread(target=bump) for _ in range(2)]
for t in ts: t.start()
for t in ts: t.join()
print('counter (may be < 200000):', counter)

Lock to the Rescue

A threading.Lock ensures only one thread enters a critical section at a time. Acquire it with a with block around the shared update.

import threading

counter = 0
lock = threading.Lock()

def bump():
    global counter
    for _ in range(100000):
        with lock:
            counter += 1

ts = [threading.Thread(target=bump) for _ in range(2)]
for t in ts: t.start()
for t in ts: t.join()
print('counter:', counter)

All lessons in this course

  1. Threads and the GIL
  2. ThreadPoolExecutor
  3. multiprocessing Basics
  4. Sharing Data Safely
← Back to Python Academy