Home >Backend Development >Python Tutorial >Race Condition in Python.
A race condition in Python refers to what happens when two or more threads or processes try to access and modify the same shared resource at the same time. The behavior of the program depends on their execution timing.
Cause: Lack of proper synchronization mechanism.
Impact: Causes unpredictable or incorrect results as threads "race" to complete their operations first.
Example:
<code class="language-python">counter = 0 def increment(): global counter for _ in range(1000): counter += 1 # 此处不是线程安全的 thread1 = threading.Thread(target=increment) thread2 = threading.Thread(target=increment) thread1.start() thread2.start() thread1.join() thread2.join() print(counter) # 输出可能会有所不同,并且小于 2000</code>
Lock
or RLock
) to ensure that only one thread accesses the critical section at a time. <code class="language-python">import threading counter = 0 lock = threading.Lock() def increment(): global counter for _ in range(1000): with lock: # 确保一次只有一个线程访问此代码块 counter += 1 thread1 = threading.Thread(target=increment) thread2 = threading.Thread(target=increment) thread1.start() thread2.start() thread1.join() thread2.join() print(counter) # 输出将始终为 2000</code>
The above is the detailed content of Race Condition in Python.. For more information, please follow other related articles on the PHP Chinese website!