python的多处理中是否存在同步问题?

2024-04-26 08:47:48 发布

您现在位置:Python中文网/ 问答频道 /正文

程序如下所示,我使用python多处理包中的函数imap_unorder

from multiprocessing import Pool

def f(x):
    return x,x*x

x_list = []
y_list = []
with Pool(processes=2) as pool:
    for x,y in pool.imap_unordered(f, range(4)):
        x_list.append(x)
        y_list.append(y)

x_列表和y_列表是否保持一致

我知道函数imap_unordered不会按顺序处理输入迭代器。但是当输出x和y时,它们能同时附加到列表中吗

x_list = [0,3,1,2]y_list = [0,9,1,4]就是一个正确的例子

但是我不想输出x_list = [0,3,1,2]y_list = [0,1,9,4]

非常感谢


2条回答

x,y值将始终保持一致,因为当您将f()的结果合并到x_listy_list中时,您回到了主进程中

为了更清楚地说明这一点,请使f()调用花费不同的时间,如下所示:

from multiprocessing import Pool
import random
import time

def f(x):
    print( f"{x=}" )
    delay = 2.0*random.random()
    print( f"{delay=}" )
    time.sleep(delay)
    return x,x*x

x_list = []
y_list = []

if __name__ == "__main__":
    with Pool() as pool:
        for x,y in pool.imap_unordered(f, range(10)):
            x_list.append(x)
            y_list.append(y)
    print( f"{x_list=}" )
    print( f"{y_list=}" )

您可能会得到这样的输出,注意到f()的并发执行是如何导致其print语句与其他也执行其f()的进程交错的:

x=0
delay=1.2836811458870878
x=1
delay=0.944416583067992
x=2
x=3
x=4
delay=1.6181526174149976
delay=0.5554265852002582
delay=1.5824716636923408
x=5
delay=0.01722248285756467
x=6
delay=1.8688128104508799
x=7
delay=0.9426899102018951
x=8
delay=0.5319453505012279
x=9
delay=0.24791521653497783
x_list=[5, 3, 8, 9, 1, 7, 0, 4, 2, 6]
y_list=[25, 9, 64, 81, 1, 49, 0, 16, 4, 36]

检查打印输出x=5的睡眠时间最短,因此在结果列表中排名第一。类似的x=6具有最长的睡眠时间,因此是输出中的最后一个睡眠时间

这些对在内部是一致的,但是使用imap_unordered()不能保证它们与输入iterable的顺序相同

您还可以使用zip()将对列表转换为一对列表:

with Pool(processes=4) as pool:
    pairs = pool.imap_unordered(f, range(10))
    x_list, y_list = zip(*pairs)

相关问题 更多 >