为什么python多处理中的函数需要多个参数?

时间:2018-06-06 16:05:51

标签: python multiprocessing

这是Python的演示代码

from multiprocessing import Process, Manager

def f(d, l):
    d[1] = '1'
    d['2'] = 2
    d[0.25] = None
    l.reverse()

if __name__ == '__main__':
    with Manager() as manager:
        d = manager.dict()
        l = manager.list(range(10))

        p = Process(target=f, args=(d, l))
        p.start()
        p.join()

        print(d)
        print(l)

它工作和输出

{0.25: None, 1: '1', '2': 2}
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

但是,如果我删除了d变量

from multiprocessing import Process, Manager

def f(l):
    l.reverse()

if __name__ == '__main__':
    with Manager() as manager:
        l = manager.list(range(10))

        p = Process(target=f, args=(l))
        p.start()
        p.join()

        print(l)

它失败并显示以下输出消息

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Process Process-2:
Traceback (most recent call last):
  File "/home/yangzh/anaconda3/lib/python3.6/multiprocessing/process.py", line 258, in _bootstrap
    self.run()
  File "/home/yangzh/anaconda3/lib/python3.6/multiprocessing/process.py", line 93, in run
    self._target(*self._args, **self._kwargs)
TypeError: f() takes 1 positional argument but 10 were given

为什么函数f()需要多个参数?使用伪参数作为解决方案似乎非常愚蠢。

0 个答案:

没有答案