S
S
sharkyyy32019-10-16 13:27:21
Python
sharkyyy3, 2019-10-16 13:27:21

Why can't start processes in multiprocessing?

from multiprocessing import Process
import time

def test_multiprocessing():

            def func1():
                print('test1')
                time.sleep(10)
            def func2():
                print('test2')
                time.sleep(5)

            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()

After executing the code, errors follow:
Traceback (most recent call last):
  File "C:/Users/Admin/PycharmProjects/asy/main_asy.py", line 32, in <module>
    test_multiprocessing()
  File "C:/Users/Admin/PycharmProjects/asy/main_asy.py", line 24, in test_multiprocessing
    p_func1.start()
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python35\lib\multiprocessing\process.py", line 105, in start
    self._popen = self._Popen(self)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python35\lib\multiprocessing\context.py", line 212, in _Popen
    return _default_context.get_context().Process._Popen(process_obj)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python35\lib\multiprocessing\context.py", line 313, in _Popen
    return Popen(process_obj)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python35\lib\multiprocessing\popen_spawn_win32.py", line 66, in __init__
    reduction.dump(process_obj, to_child)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python35\lib\multiprocessing\reduction.py", line 59, in dump
    ForkingPickler(file, protocol).dump(obj)
AttributeError: Can't pickle local object 'test_multiprocessing.<locals>.func1'

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
tsarevfs, 2019-10-16
@tsarevfs

It does not cope with the local declaration of func1 and func2. Just declare them at the same level as test_multiprocessing.

S
ScriptKiddo, 2019-10-16
@ScriptKiddo

spoiler

from multiprocessing import Process
import time

print(1)


def func1():
    print('test1')
    time.sleep(10)


def func2():
    print('test2')
    time.sleep(5)


def test_multiprocessing():
    p_func1 = Process(target=func1)
    p_func2 = Process(target=func2)
    p_func1.start()
    p_func2.start()
    p_func1.join()
    p_func2.join()
    print('done')


if __name__ == '__main__':
    test_multiprocessing()

out:
1
11

test2
test1
done

Process finished with exit code 0

Python 3.7 64bit Windows 10 1903

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question