Junior — Middle
In what cases does data race occur in Python when working with multithreading?
sobes.tech AI
Answer from AI
Data race condition in Python occurs when multiple threads access and modify shared mutable data simultaneously without proper synchronization. For example, if two threads increment a shared counter at the same time, the final value may be incorrect due to operation interruption.
This happens because read and write operations are not atomic, and context switching between threads can lead to lost updates.
To prevent data races, synchronization mechanisms such as Lock and RLock from the threading module are used:
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) # Should be 1000
Without the lock, the final value can be less than expected due to race conditions.