Junior — Middle
What methods and tools have you used to prevent race conditions in Python development?
sobes.tech AI
Answer from AI
To prevent race conditions in Python, various synchronization methods are used, especially when working with threads or processes:
- Lock from the
threadingmodule — allows restricting access to a critical section of code to one thread. - RLock (reentrant lock) — allows a thread to acquire the lock multiple times.
- Semaphore — limits the number of threads that can execute a certain section of code simultaneously.
- Queue — a thread-safe queue that helps safely exchange data between threads.
Example of using Lock to protect a shared resource:
import threading
counter = 0
lock = threading.Lock()
def increment():
global counter
with lock:
temp = counter
temp += 1
counter = temp
threads = [threading.Thread(target=increment) for _ in range(1000)]
for t in threads:
t.start()
for t in threads:
t.join()
print(counter) # Expected 1000
Without locking, the value of counter could be less due to concurrent access and overwriting.