0

第一个 ''' 将多处理导入为 mp

def func( list):
    x = 5
    list = list*5
    print('list_in_sub: ', list)

if __name__ == "__main__":
    list = mp.Manager().list(range(2))  
    p1 = mp.Process(target=func, args=( list,))
    p1.start()
    p1.join()

    print('list_in_main: ', list)

''' 结果:list_in_sub: [0, 1, 0, 1, 0, 1, 0, 1, 0, 1] list_in_main: [0, 1]

第二个 ''' 将多处理导入为 mp

def func(list):
    x = 5
    list = list.append(x)
    print('list_in_sub: ', list)

if __name__ == "__main__":
    list = mp.Manager().list(range(2))  
    p1 = mp.Process(target=func, args=(list,))
    p1.start()
    p1.join()

    print('list_in_main: ', list)

''' 结果:list_in_sub: 无 list_in_main: [0, 1, 5]

4

1 回答 1

0

第一个应该是:

import multiprocessing as mp

def func(list):
    x = 5
    list *= 5
    print('list_in_sub: ', list)

if __name__ == "__main__":
    list = mp.Manager().list(range(2))  
    p1 = mp.Process(target=func, args=( list,))
    p1.start()
    p1.join()

    print('list_in_main: ', list)

# list_in_sub:  [0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
# list_in_main:  [0, 1, 0, 1, 0, 1, 0, 1, 0, 1]

第二个应该是:

import multiprocessing as mp

def func(list):
    x = 5
    list.append(x)
    print('list_in_sub: ', list)

if __name__ == "__main__":
    list = mp.Manager().list(range(2))  
    p1 = mp.Process(target=func, args=(list,))
    p1.start()
    p1.join()

    print('list_in_main: ', list)

# list_in_sub:  [0, 1, 5]
# list_in_main:  [0, 1, 5]

解释:

  • 对于第一个,在函数内部list = list*5定义一个新变量list。由于这与list收到的不同,因此内容不同。相反,list *= 5就地更新变量。
  • 第二个是bug。 .append方法将新值添加到列表中,并且不返回任何内容。因此,list = list.append(x)添加x到原始列表中,并list在函数内将新变量定义为 None。
  • 注:list是保留关键字;您可能希望使用不同的变量名来避免错误。

上面的示例可能不是那么有趣,因为列表仅由一个进程更新。下面演示了两个进程以随机顺序共享和更新同一个列表。

import multiprocessing as mp

def add_positive(lst):
    for i in range(1, 31):
       lst.append(i)

def add_negative(lst):
    for i in range(1, 31):
       lst.append(-i)
        
if __name__ == "__main__":
    lst = mp.Manager().list([0])  
    p1 = mp.Process(target=add_positive, args=(lst,))
    p2 = mp.Process(target=add_negative, args=(lst,))
    p1.start()
    p2.start()
    p1.join()
    p2.join()

    print('Result: ', lst)

#Result (order should vary):  
#[0, 1, 2, 3, 4, -1, 5, -2, 6, -3, 7, -4, -5, 8, -6, 9, -7, 10, -8, 
#11, -9, 12, -10, 13, -11, -12, 14, -13, 15, -14, 16, -15, 17, -16, 
#18, -17, 19, -18, 20, -19, 21, -20, -21, 22, -22, 23, -23, 24, -24, 
#25, -25, 26, -26, 27, -27, 28, -28, 29, -29, 30, -30]
于 2021-09-03T04:08:05.003 回答