
问题提出
在涉及多进程共享可操作变量时,确保原子性操作至关重要,尤其是在对该变量进行增减或比较等操作时。
原因分析
在多进程场景下,多个进程会并发访问共享变量,如果不采取保护措施,可能会出现竞态条件,导致意外结果。例如,多个进程读取到相同的值,然后分别执行增减操作,最终结果与预期不符。
解决方案
可以使用以下方法确保原子性操作:
创建 manager 对象和锁
使用 multiprocessing.manager() 创建一个管理器对象,以允许进程间共享变量。然后,创建一把锁,用 multiprocessing.lock() 创建。
在计算函数中使用锁
在每个计算函数中,在修改共享变量之前,使用锁保护该部分代码。这样可以确保在任何时刻只有一个进程访问共享变量。
示例代码
以下是经过修改的示例代码,启用了原子性操作:
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: ValueProxy, total_tasks: int, _lock):
# 模拟耗时计算
res = x**y
# 使用锁保证原子性操作
with _lock:
_m.value += 1
current_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()通过这些修改,即使在多进程环境中,共享变量的读取和增减操作也可以得到保证的原子性,从而避免了竞态条件。
以上就是多进程编程中,如何保证共享变量的原子操作?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号