Skip to main content
 首页 » 编程设计

python之在循环中使用 multiprocessing.pool 并更新目标函数

2024年10月01日6zengkefu

我有一个关于 python Multiprocessing.pool 的快速问题。这是我的代码:

import multiprocessing as mp  
 
info =999 
def func(x): 
    global info 
    print info 
    return x**3 
 
pool = mp.Pool() 
for i in range(2): 
    print "Iteration: ", i 
    results = pool.map(func, range(1,10)) 
    print "Value of info", info 
    info += 1 
    print results  
    print "Iteration", i, "End" 
    print 

输出看起来像这样:

999 
999 
999 
999 
999 
999 
999 
999 
999 
999 
999 
999 
999 
999 
999 
999 
999 
999 
Iteration:  0 
Value of info 999 
[1, 8, 27, 64, 125, 216, 343, 512, 729] 
Iteration 0 End 
 
Iteration:  1 
Value of info 1000 
[1, 8, 27, 64, 125, 216, 343, 512, 729] 
Iteration 1 End 

我想知道为什么在第二次迭代中再次打印 999 而不是 1000。如何更新全局变量信息以便在第二次迭代中打印 1000?非常感谢!

请您参考如下方法:

评论已经说明了一点。我想我会解释得更多一些。

当使用 multiprocessing 模块时,它将根据 pool 中请求的进程数创建新进程。默认值由 multiprocessing.cpu_count() 计算。

假设您编写的脚本是 A.py,它创建了进程 A。当A 创建新进程时,它们被称为A 的子进程。这些子进程将具有相同的全局变量,并以 A 开头。

但是,每个子进程都有自己的作用域,因此更改一个子进程中的变量 info 不会影响其他子进程中 info 的值。而且它肯定不会影响父进程 A 中的值。

一个简单的解决方案是指示每个子进程向父进程A 报告所需的info 更改。也就是说,map 中的每个子进程都应返回 -1 作为结果,而父进程 A 会在其自己的范围内聚合更新。在分布式计算中,这称为参数服务器设计。

在理想世界中,您真正想要的是共享范围和内存的线程。但是 Python 线程会因为 Global Interpreter Lock 而变得非常复杂。如果您有兴趣,可以对此进行一些 Google 搜索。


我误读了您的代码。在我的脑海里,凌晨 2 点,我阅读了子项中 info 的修改和父项中的打印。事实上恰恰相反。

你是正确的,关键是修改不会跨进程共享。如果您使用 global 访问子进程中的 info,子进程将不会意识到更改,因为该函数在创建时被 pickled模块的时间。您可以在 http://grahamstratton.org/straightornamental/entries/multiprocessing 继续阅读

您需要将动态 info 作为函数的参数发送给它,如下所示:

import multiprocessing as mp 
 
def dual_input(t): 
    info, x = t 
    print info 
    return x**3 
 
def main(): 
    info =999 
    pool = mp.Pool(2) 
    for i in range(2): 
        print "Iteration: ", i 
        results = pool.map(dual_input, zip([info]*9, range(1,10))) 
        print "Value of info", info 
        info += 1 
        print results 
        print "Iteration", i, "End" 
        print 
 
 
if __name__ == '__main__': main() 

上面的代码打印:

Iteration:  0 
999 
999 
999 
999 
999 
999 
999 
999 
999 
Value of info 999 
[1, 8, 27, 64, 125, 216, 343, 512, 729] 
Iteration 0 End 
 
Iteration:  1 
1000 
1000 
1000 
1000 
1000 
1000 
1000 
1000 
1000 
Value of info 1000 
[1, 8, 27, 64, 125, 216, 343, 512, 729] 
Iteration 1 End