Can't call multiple functions in the same time with multiprocessing

こ雲淡風輕ζ 提交于 2021-02-05 06:36:27

问题


I'm trying to figure out how could I run the same function multiple times in the same time. I could implement something with the multiprocessing that based on other SO questions, but unfortunately it doesn't work as I wanted. Actually when I run it I get something like this (the functions are running after each osther):

Worker1
0 1
1 1
2 1
Worker2
0 2
1 2
2 2
Worker3
0 3
1 3
2 3  

And I would like to achieve this (or something like this):

Worker1
Worker2
Worker3
0 1
0 2
0 3
1 1
1 2
1 3
2 1
2 2
2 3

I'm really new to Python so it's possible that've made some trivial mistakes, but unfortunately I can't figure out where's the problem, so I would really appreciate if somebody could show me the right solution.

import multiprocessing

def worker():
    print ("Worker1")
    doSomething(1)
    return

def worker2():
    print ("Worker2")
    doSomething(2)
    return              


def worker3():
    print ("Worker3")
    doSomething(3)
    return    


def doSomething (x):
    for num in range(3): 
        print (num, x)


def runInParallel(*fns):
  proc = []
  for fn in fns:
    p = multiprocessing.Process(target=fn)
    p.start()
    proc.append(p)
  for p in proc:
    p.join()


if __name__ == '__main__':
    runInParallel(worker, worker2, worker3)

 # 2. ATTEMPT - it does the same
if __name__ == '__main__':
    p = multiprocessing.Process(target=worker)
    jobs.append(p)
    p.start()
    p2 = multiprocessing.Process(target=worker2)
    jobs.append(p2)
    p2.start()
    p3 = multiprocessing.Process(target=worker3)
    jobs.append(p3)
    p3.start()

回答1:


What is happening, is that the background thread is finishing even before the program can create and start the next thread, so that is why you are getting each worker separated. To get the output you want. You can add a sleep, like Evert mentioned:

def doSomething (x):
    time.sleep(.01)
    for num in range(3):
        print (num, x)


来源:https://stackoverflow.com/questions/34644660/cant-call-multiple-functions-in-the-same-time-with-multiprocessing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!