Junior — Middle
Explain what a data race condition is in Python applications and why it is dangerous?
sobes.tech AI
Answer from AI
A race condition in Python occurs when multiple threads access and modify a shared resource simultaneously without proper synchronization. This leads to unpredictable program behavior and errors.
Why is this dangerous:
- The program's outcome becomes unstable and depends on the order of thread execution.
- Hard-to-reproduce bugs may occur.
- Data integrity is compromised, which can lead to program state corruption.
Example:
import threading
counter = 0
def increment():
global counter
for _ in range(100000):
counter += 1 # non-atomic operation
threads = [threading.Thread(target=increment) for _ in range(2)]
for t in threads:
t.start()
for t in threads:
t.join()
print(counter) # expected 200000, but may be less due to race conditions
To prevent race conditions, use locks (threading.Lock) or other synchronization mechanisms.