Junior — Middle
How can race conditions be prevented in multithreaded programs?
sobes.tech AI
Answer from AI
Race conditions occur when multiple threads access shared resources simultaneously without proper synchronization, leading to unpredictable program behavior.
To prevent race conditions in Python, you can use:
- Locks from the
threadingmodule. They ensure that only one thread executes a critical section of code at a specific time. - Semaphores to limit the number of threads working with a resource simultaneously.
- Mutexes — specialized locks.
- Thread-safe data structures, such as those from the
queuemodule.
Example using a lock:
import threading
counter = 0
lock = threading.Lock()
def increment():
global counter
with lock: # Critical section
temp = counter
temp += 1
counter = temp
threads = []
for _ in range(1000):
t = threading.Thread(target=increment)
threads.append(t)
t.start()
for t in threads:
t.join()
print(counter) # Expected 1000
Without a lock, the value of counter can be less than 1000 due to race conditions.