如何调用简单函数并同时在Python中运行以下行?

问题描述 投票:0回答:1

我知道有一个叫做线程的东西,但是我对整个Google的那些复杂信息感到困惑。 myFunc()需要一点时间(计算上并不昂贵,比如播放一个简短的mp3文件)。我想做的就是调用myFunc(),而不必等待它返回以运行以下代码行。此外,我不需要保留任何与myFunc(arg)相关的内容,只需要执行它即可。

while(True):
    ......
    myFunc(arg)
    ###some
    ###lines
    ###of
    ###code

对不起,我的英语不好。干杯!

python multithreading python-multithreading
1个回答
1
投票
from threading import Thread

def myFunc(arg):
    # run code here

while(True):
    thread = Thread(target = myFunc, args = (arg, ))
    thread.start() # starts the thread, executes the function
    ###some
    ###lines
    ###of
    ###code
    thread.join() # wait for myFunc to finish

您可以类似地使用进程而不是线程。

如果要使用相同的功能执行参数列表,则可能要查看池。您可以调用imap并迭代结果,然后调用其余代码。

© www.soinside.com 2019 - 2024. All rights reserved.