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.Queuefor producer/consumer.
The GIL does not make your code thread-safe; it only protects the interpreter's internals.
More on Concurrency: threads, processes & asyncio
What is the GIL, and what does it mean for DevOps scripts?IntermediateHow do you use `ThreadPoolExecutor` for parallel API calls?BeginnerThreads vs processes vs asyncio: how do you choose?IntermediateHow does a producer/consumer pattern with `queue.Queue` work?AdvancedWhat are coroutines, `async def` and `await`?IntermediateHow do you run many async tasks concurrently with a limit?Intermediate