多处理不能同时调用多个函数 [英] Can't call multiple functions in the same time with multiprocessing

查看:58
本文介绍了多处理不能同时调用多个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚如何在同一时间多次运行同一个函数.我可以使用基于其他 SO 问题的多处理来实现一些东西,但不幸的是它不能按我想要的方式工作.实际上,当我运行它时,我得到了这样的东西(函数在每个 osther 之后运行):

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

我对 Python 真的很陌生,所以可能犯了一些小错误,但不幸的是我无法弄清楚问题出在哪里,所以如果有人能向我展示正确的解决方案,我将不胜感激.

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

推荐答案

发生了什么,甚至在程序可以创建和启动下一个线程之前后台线程就已经完成了,这就是为什么你要让每个工作线程分离.得到你想要的输出.你可以添加睡眠,就像埃弗特提到的:

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)

这篇关于多处理不能同时调用多个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆