我正在阅读和应用python书中的代码,我不能在简单的例子中使用多处理,你可以在下面看到:
import multiprocessing
def myProcess():
print("Currently Executing Child Process")
print("This process has it's own instance of the GIL")
print("Executing Main Process")
print("Creating Child Process")
myProcess = multiprocessing.Process(target=myProcess)
myProcess.start()
myProcess.join()
print("Child Process has terminated, terminating main process")
我的平台是 Windows 10 64 位,使用 if __name_ == "__main_" :在这种情况下不起作用。这是怎么回事?此代码应该适用于 python 版本 3.5 及更高版本。我使用的Python版本是3.7。完整的错误消息如下:
C:UsersXianAppDataLocalProgramsPythonPython37-32python.exe "C:/OneDrive/Utilizing sub-process.py"
Traceback (most recent call last):
File "C:/OneDrive/Utilizing sub-process.py", line 25, in <module>
myProcess.start()
File "C:UsersXianAppDataLocalProgramsPythonPython37-32libmultiprocessingprocess.py", line 112, in start
self._popen = self._Popen(self)
File "C:UsersXianAppDataLocalProgramsPythonPython37-32libmultiprocessingcontext.py", line 223, in _Popen
return _default_context.get_context().Process._Popen(process_obj)
File "C:UsersXianAppDataLocalProgramsPythonPython37-32libmultiprocessingcontext.py", line 322, in _Popen
return Popen(process_obj)
File "C:UsersXianAppDataLocalProgramsPythonPython37-32libmultiprocessingpopen_spawn_win32.py", line 65, in __init__
reduction.dump(process_obj, to_child)
File "C:UsersXianAppDataLocalProgramsPythonPython37-32libmultiprocessingreduction.py", line 60, in dump
ForkingPickler(file, protocol).dump(obj)
_pickle.PicklingError: Can't pickle <function myProcess at 0x02B2D420>: it's not the same object as __main__.myProcess
试试这个
def test()
import multiprocessing
multiprocessing.set_start_method("fork")
p = multiprocessing.Process(target=xxx)
p.start()
python 多处理上下文和启动方法