Interview Prep/Python for DevOps/Concurrency: threads, processes & asyncio

What is a race condition, and how do you prevent one in threaded code?

IntermediateConceptConcurrency: threads, processes & asyncio
Answer

A race happens when threads read-modify-write shared state without coordination, for example counter += 1 (load, add, store) from 20 threads losing increments.

  • Avoid shared mutable state: have workers return results and aggregate in the main thread.
  • If you must share, protect with threading.Lock() (with lock: counter += 1).
  • Use thread-safe structures: queue.Queue for producer/consumer.

The GIL does not make your code thread-safe; it only protects the interpreter's internals.

All Python for DevOps questions Roadmap: Python for automation

More on Concurrency: threads, processes & asyncio