I'm a beginner of python, I'm trying to put multiprocessing into a function, however python gives me an error.
Please refer the original code as below:
from multiprocessing import Process
import time
def func1():
print('test1')
time.sleep(10)
def func2():
print('test2')
time.sleep(5)
if __name__ == '__main__':
p_func1 = Process(target=func1)
p_func2 = Process(target=func2)
p_func1.start()
p_func2.start()
p_func1.join()
p_func2.join()
print('done')
It runs well and give the correct result I need.
However, when I tried to put the multiprocessing code into function:
from multiprocessing import Process
import time
def test_multiprocessing():
def func1():
print('test1')
time.sleep(10)
def func2():
print('test2')
time.sleep(5)
if __name__ == '__main__':
p_func1 = Process(target=func1)
p_func2 = Process(target=func2)
p_func1.start()
p_func2.start()
p_func1.join()
p_func2.join()
print('done')
test_multiprocessing()
Below is error I got, may I know how to fix this issue ? The reason I'd like to put multiprocessing into a funciton is because there is an existing code there, and I don't want to do major change of the code to support multiprocessing.
Traceback (most recent call last):
File "multipleprocessing.py", line 20, in <module>
test_multiprocessing()
File "multipleprocessing.py", line 14, in test_multiprocessing
p_func1.start()
File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\multiprocessing
\process.py", line 105, in start
self._popen = self._Popen(self)
File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\multiprocessing
\context.py", line 223, in _Popen
return _default_context.get_context().Process._Popen(process_obj)
File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\multiprocessing
\context.py", line 322, in _Popen
return Popen(process_obj)
File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\multiprocessing
\popen_spawn_win32.py", line 65, in __init__
reduction.dump(process_obj, to_child)
File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\multiprocessing
\reduction.py", line 60, in dump
ForkingPickler(file, protocol).dump(obj)
AttributeError: Can't pickle local object 'test_multiprocessing.<locals>.func1'
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\multiprocessing
\spawn.py", line 99, in spawn_main
new_handle = reduction.steal_handle(parent_pid, pipe_handle)
File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\multiprocessing
\reduction.py", line 87, in steal_handle
_winapi.DUPLICATE_SAME_ACCESS | _winapi.DUPLICATE_CLOSE_SOURCE)
PermissionError: [WinError 5] Access is denied
Per tested code on Linux, it works. Does that mean Windows Python can't support multiprocessing in function?