
多线程或多进程并发访问和修改同一共享资源时,可能出现竞争条件,导致程序结果依赖于线程或进程的执行顺序。
<code class="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>如果没有正确的同步,线程会互相干扰,导致最终结果不确定。
threading.Lock 或 threading.RLock)保护临界区,确保同一时间只有一个线程访问共享资源。<code class="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>以上就是Python 中的竞争条件的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号