我在多處理中遇到了一個奇怪的行爲。多進程不會看到全局變量?
當我嘗試在從多處理調用的函數中使用全局變量時,它看不到全局變量。
例子:
import multiprocessing
def func(useless_variable):
print(variable)
useless_list = [1,2,3,4,5,6]
p = multiprocessing.Pool(processes=multiprocessing.cpu_count())
variable = "asd"
func(useless_list)
for x in p.imap_unordered(func, useless_list):
pass
輸出:
asd
multiprocessing.pool.RemoteTraceback:
"""
Traceback (most recent call last):
File "/usr/lib/python3.4/multiprocessing/pool.py", line 119, in worker
result = (True, func(*args, **kwds))
File "pywork/asd.py", line 4, in func
print(variable)
NameError: name 'variable' is not defined
"""
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "pywork/asd.py", line 11, in <module>
for x in p.imap_unordered(func, useless_list):
File "/usr/lib/python3.4/multiprocessing/pool.py", line 689, in next
raise value
NameError: name 'variable' is not defined
正如你看到的,我第一次只是簡單地調用func
其打印asd
預期。但是,當我用多處理函數調用相同的函數時,它說變量variable
不存在,即使在我明確地將它打印之前。
多處理忽略全局變量嗎?我怎樣才能解決這個問題?