
多线程或多进程并发访问和修改同一共享资源时,可能出现竞争条件,导致程序结果依赖于线程或进程的执行顺序。
关键点:
- 成因: 缺乏合适的同步机制。
- 后果: 产生不可预测或错误的结果,因为线程之间存在资源竞争。
- 示例: 两个线程同时更新一个共享计数器:
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,不可预测
如果没有正确的同步,线程会互相干扰,导致最终结果不确定。
让 macOS 自动化像说话一样简单 —— 用代码控制你的 Mac,无需学习 AppleScript 系统要求 macOS 14+ (Sonoma) Python 3.9+ 需要开启:辅助功能 + 屏幕录制权限
如何避免竞争条件:
- 使用锁(例如
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
面试技巧:
- 竞争条件源于对共享资源的非同步访问。
- 解决方法是使用锁或其他同步机制。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










