本站资源收集于互联网,不提供软件存储服务,每天免费更新优质的软件以及学习资源!

Python多进程共享变量如何保证原子操作?

网络教程 app 1℃

Python多进程共享变量如何保证原子操作

python多进程共享可操作变量, 如何保证原子操作?

需求分析

为了确保多进程共享可操作变量的原子操作,需要:

维护一个共享变量:使用多处理模块中的manager对象可以创建共享变量。实现原子操作:使用锁机制来保证共享变量的修改在任意时刻仅由一个进程执行。

问题场景

在本文给出的演示代码中,使用共享变量作为计数器,当多个进程同时读取和修改它时,会出现竞争条件,导致变量值不正确。

解决方案

解决此问题的关键是确保共享变量的修改操作是原子的。修改后的代码如下:

from concurrent.futures import ProcessPoolExecutorimport ctypesfrom multiprocessing import Manager, Lockimport os# 创建 Manager 和 Lockmanager = 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()

说明

使用manager创建共享变量m和锁lock。calc_number函数中使用with锁来保证m.value的修改操作是原子的。即,每次只有一个进程可以访问m.value。这样就避免了多个进程同时读取和修改变量的问题,确保了原子操作。

以上就是Python多进程共享变量如何保证原子操作?的详细内容,更多请关注范的资源库其它相关文章!

转载请注明:范的资源库 » Python多进程共享变量如何保证原子操作?

喜欢 (0)