I am new in python i have Anaconda Pyton 3.9 I was studying about Multiprocessing.
When i try this code
from multiprocessing import Process # gerekli kütüphaneyi çağıracağız.
import time
def subfunc1():
time.sleep(2)
print("subfunc1: Baslatildi")
time.sleep(2)
print("subfunc1: Sonlandi")
time.sleep(2)
def subfunc2():
time.sleep(2)
print("subfunc2: Baslatildi")
time.sleep(2)
print("subfunc2: Sonlandi")
time.sleep(2)
def mainfunc():
print("mainfunc: Baslatildi")
pr1 = Process(target=subfunc1)
pr2 = Process(target=subfunc2)
pr1.start()
pr2.start()
print("mainfunc: Sonlandi")
if __name__ == '__main__': # Main kod bloğunun içerisindeyken main fonk çağır!
mainfunc()
result is
mainfunc: Baslatildi
mainfunc: Sonlandi
When i use Visual Code with Python 3.9 i have a virtual and code works! Visual Code uses Anaconda's python 3.9 within a virtual env!
Could you please help me? Whey this code can't work properly in Jupyter Notebook?
Thanks
Am I correct in assuming you are running this on ms-windows or macOS?
In that case, multiprocessing
will not work in an interactive interpreter like IPython. This is covered in the documentation, see the "note":
Functionality within this package requires that the
__main__
module be importable by the children. This is covered in Programming guidelines however it is worth pointing out here. This means that some examples, such as themultiprocessing.pool.Pool
examples will not work in the interactive interpreter.
This is caused by the spawn
start method used on these operating systems.
One possible fix is to save you code in a script, and to make sure that creating multiprocessing
objects is done within the __main__
-block. Another is in the comment by Aaron below