2

i try to run simple example of multiprocessing but it is not working

when i try to run the same function with threading or in regular way in working

with multiprocessing (not working):


import multiprocessing 

def do_something():
    print('Sleeping 1 second...')
    time.sleep(1)
    print('Done sleeping')

p1 = multiprocessing.Process(target=do_something)
p2 = multiprocessing.Process(target=do_something)

p1.start()
p2.start()

with threading (working):


import threading

def do_something():
    print('Sleeping 1 second...')
    time.sleep(1)
    print('Done sleeping')

t1 = threading.Thread(target=do_something)
t2 = threading.Thread(target=do_something)
t1.start()
t2.start()

orial
  • 21
  • 2
  • I ran the code and both example worked on my jupyter notebook. This might help: https://stackoverflow.com/questions/47313732/jupyter-notebook-never-finishes-processing-using-multiprocessing-python-3 – Zabir Al Nazi Apr 27 '20 at 20:50
  • Try putting parentheses after the do_something fuction call like `do_something()` . Your code ran after I added the parentheses, but it wasn't spawning multiple processes – Trace Malloc Apr 27 '20 at 20:56
  • Please give us the error message or other explanation why it is not working. You should also tell us about your environment. This is one of the cases where it matters if you are on a mac, linux or windows. – Hannu Sep 13 '21 at 19:43
  • Parentheses are definitely not the thing to do here. Yes, the code probably runs if the problem is where I expect it to be, but it does not create processes. It just runs the function on the spot. – Hannu Sep 13 '21 at 19:47
  • Thread version works, but it still does not run in parallel. Take a look to the task manager and see that cpu usage is just 1 core. (experience on Windows, maybe it's different on other os) – Armando Contestabile Dec 27 '22 at 17:48

1 Answers1

0

In order the code to work correctly, you need to put all requirements inside one cell and then run it.

from multiprocessing import Pool
import other/modules/...

def do_something(arg1):
    print('Sleeping 1 second...')
    time.sleep(1)
    print('Done sleeping')

if __name__ == '__main__':
   pool = Pool(os.cpu_count()) 
   pool.map(do_something, list_of_args)
Baran
  • 1