简体   繁体   English

function 看起来如何,可以将另一个 function 添加到在 python 中并行运行的函数列表中?

[英]How could a function look like, that can add an other function to a list of functions that run parallel in python?

def update():
   while True:
       loadData()

def main():
   doStuff()
   addToParallelFunctions(update)
   doOtherStuff()

if __name__ == '__main__':
   addToParallelFunctions(main)

How could that addToParallelFunctions function look like, so that update runs parallel to main and that I can add other functions to run also parallel to the main ? addToParallelFunctions function 怎么可能看起来像这样,以便 update 与main并行运行,并且我可以添加其他函数以也与main并行运行?

I've tried that, but it paused the main function and ran the other function until she was finished.我试过了,但它暂停了主要的 function 并运行了另一个 function 直到她完成。

from multiprocessing import Process

def addProcess(*funcs):
    for func in funcs:
       Process(target=func).start()

I enhanced your example: It works for me.我增强了您的示例:它对我有用。 Main script and function continue both.主脚本和 function 继续。

import time
from multiprocessing import Process

def addProcess(*funcs):
    for func in funcs:
       Process(target=func).start()

def update():
   for i in range(20):
       print(i)
       time.sleep(2)

def main():
   print("start")
   addProcess(update)
   print("Main function continues")

if __name__ == '__main__':
   addProcess(main)
   print("main script continues")

Next time, please post an example that is reproducible.下次,请发布一个可重现的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM