gpt4 book ai didi

python - 为什么 multiprocessing.Process 能够 pickle 修饰函数?

转载 作者:太空宇宙 更新时间:2023-11-03 11:03:34 29 4
gpt4 key购买 nike

所以我读了here不能 pickle 装饰函数。确实:

import multiprocessing as mp

def deco(f):
def wrapper(*args, **kwargs):
try:
f(*args, **kwargs)
except:
print 'Exception caught!'
return wrapper

@deco
def f(x):
print x
raise OverflowError

if __name__ == '__main__':
pool = mp.Pool(processes=1)
for _ in pool.imap_unordered(f, range(10)):
pass
pool.close()
pool.join()
print 'All done'

输出:

Traceback (most recent call last):
File "deco0.py", line 19, in <module>
for _ in pool.imap_unordered(f, range(10)):
File "/Users/usualme/anaconda/lib/python2.7/multiprocessing/pool.py", line 659, in next
raise value
cPickle.PicklingError: Can't pickle <type 'function'>: attribute lookup __builtin__.function failed

但是现在,如果我用 Process 替换 map:

import multiprocessing as mp

def deco(f):
def wrapper(*args, **kwargs):
try:
f(*args, **kwargs)
except:
print 'Exception caught!'
return wrapper

@deco
def f(x):
print x
raise OverflowError

if __name__ == '__main__':
p = mp.Process(target=f, args=(1,))
p.start()
p.join()
print 'All done'

输出:

1
Exception caught!
All done

为什么有效?进程不需要 pickle 装饰函数吗?

最佳答案

之所以有效,是因为您在 Linux 上运行,不需要 pickle f 以通过 Process.__init__ 在子进程中调用它。这是因为 f 通过 os.fork 被 child 继承。如果您在 Windows 上运行相同的代码(缺少 fork),或者尝试将 f 传递给 Pool.apply/Pool/map(两者都需要 pickle f 才能在子进程中调用它),你会得到一个错误。

无论您使用什么平台,这个例子都会失败:

import multiprocessing as mp

def deco(f):
def wrapper(*args, **kwargs):
try:
f(*args, **kwargs)
except:
print 'Exception caught!'
return wrapper

@deco
def f(x):
print x
raise OverflowError

if __name__ == '__main__':
p = mp.Pool()
p.apply(f, args=(1,)) # f needs to be pickled here.
print 'All done'

输出:

1
Exception caught!
Exception in thread Thread-2:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 551, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 504, in run
self.__target(*self.__args, **self.__kwargs)
File "/usr/lib/python2.7/multiprocessing/pool.py", line 319, in _handle_tasks
put(task)
PicklingError: Can't pickle <type 'function'>: attribute lookup __builtin__.function failed

关于python - 为什么 multiprocessing.Process 能够 pickle 修饰函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26280733/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com