python多进程共享可操作变量, 如何保证原子操作?
需求分析
为了确保多进程共享可操作变量的原子操作,需要:
问题场景
立即学习“Python免费学习笔记(深入)”;
在本文给出的演示代码中,使用共享变量作为计数器,当多个进程同时读取和修改它时,会出现竞争条件,导致变量值不正确。
解决方案
解决此问题的关键是确保共享变量的修改操作是原子的。修改后的代码如下:
from concurrent.futures import ProcessPoolExecutor import ctypes from multiprocessing import Manager, Lock import os # 创建 Manager 和 Lock manager = Manager() m = manager.Value(ctypes.c_int, 0) lock = manager.Lock() def calc_number(x: int, y: int, _m, total_tasks: int, _lock): # 模拟耗时任务函数 # 模拟耗时计算 res = x ** y # 用锁来保证原子操作 with _lock: _m.value += 1 current_value = _m.value # 当总任务数量和_m.value相等的时候, 通知第三方任务全部做完了 if current_value == total_tasks: print(True) print(f"m_value: {current_value}, p_id: {os.getpid()}, res: {res}") def main(): # 任务参数 t1 = (100, 200, 300, 400, 500, 600, 700, 800) t2 = (80, 70, 60, 50, 40, 30, 20, 10) len_t = len(t1) # 多进程执行任务 with ProcessPoolExecutor(max_workers=len_t) as executor: for x, y in zip(t1, t2): executor.submit(calc_number, x, y, m, len_t, lock) if __name__ == "__main__": main()
说明
以上就是Python多进程共享变量如何保证原子操作?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号