第二个同时 'for loop' 执行中断第一个

second simultaneous 'for loop' execution break the first one

一年多来我用这个烂摊子同时执行'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 loops',我很乐意阅读它。

您应该使用 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()