标签导航:

python 中的竞争条件

多线程或多进程并发访问和修改同一共享资源时,可能出现竞争条件,导致程序结果依赖于线程或进程的执行顺序。

关键点:

  1. 成因: 缺乏合适的同步机制。
  2. 后果: 产生不可预测或错误的结果,因为线程之间存在资源竞争。
  3. 示例: 两个线程同时更新一个共享计数器:
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,不可预测

如果没有正确的同步,线程会互相干扰,导致最终结果不确定。

如何避免竞争条件:

  • 使用锁(例如 threading.Lock 或 threading.RLock)保护临界区,确保同一时间只有一个线程访问共享资源。
  • 使用锁的示例:
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

面试技巧:

  • 竞争条件源于对共享资源的非同步访问
  • 解决方法是使用或其他同步机制