第二个同时执行的“ for循环”执行中断了第一个

时间:2018-07-28 22:58:34

标签: python python-3.x exec

一年多来,我用这个烂摊子同时执行“ for loop”。

import time

#in actual program this is a dynamic dictionary with different amount of keys/values pairs

mydict = {1: 'czech', 2: 'dutch', 3: 'English'}

def function(id):
    time.sleep(1)
    print(mydict[id])

#if you try this code, you will see 'print' for all dictionary keys
#simultaneously, despite the fact that it's a for loop with time.sleep
#the exec here creates new function with name from 'mydict' and connects
#it to a separate process

for id in mydict:
    exec("""def func""" + str(id) + """():\n  function(id)""")
    exec("""p""" + str(id) + """ = Process(target=func""" + str(id) + """)\np""" + str(id) + """.start()""")

但是现在有时候,当其他程序(甚至具有不同的venv)尝试执行类似的代码时,已经执行该代码的第一个程序会完全中断。我认为这是由于“ exec”限制引起的,但我不确定,因为我从未见过任何错误。它只是停顿之类的。如果有人知道问题是什么以及如何对其进行调整,以便可以同时执行多个“ for循环”,那么我将很高兴阅读它。

1 个答案:

答案 0 :(得分:1)

您应该使用args参数将参数传递给目标函数,而不要使用exec来构造语句。您还应该添加if __name__ == '__main__':,以确保您的子进程不会执行与父进程相同的代码。

将您的for循环替换为:

if __name__ == '__main__':
    l = []
    for id in mydict:
        p = Process(target=function, args=(id,))
        p.start()
        l.append(p)
    for i in l:
        i.join()