Junior — Middle
What methods can be used to prevent or eliminate race conditions when working with threads in multi-process applications?
sobes.tech AI
Answer from AI
Race conditions occur when multiple threads access shared resources simultaneously and modify them without synchronization, leading to unpredictable results.
To prevent or eliminate race conditions in Python, you can use:
-
Locks — the
threading.Lockobject allows one thread to acquire a resource, blocking access for others until released. -
Semaphores — limit the number of threads working with a resource simultaneously.
-
Monitors and condition variables (Condition) — allow threads to wait for certain conditions.
-
Use of thread-safe data structures — for example, from the
queuemodule.
Example with locking:
import threading
lock = threading.Lock()
shared_resource = 0
def increment():
global shared_resource
with lock:
temp = shared_resource
temp += 1
shared_resource = temp
threads = [threading.Thread(target=increment) for _ in range(100)]
for t in threads:
t.start()
for t in threads:
t.join()
print(shared_resource) # Expected 100
Thus, thread synchronization prevents simultaneous data modification and ensures the correctness of the program.