我有两个功能,“一”和“二”。我希望函数“一”在后台作为两次运行运行。基本上,执行一个,在等待时执行两个。
import time
def one(msg, a):
time.sleep(a)
print(msg)
def two(msg, a):
time.sleep(a)
print(msg)
one("Hello, ", 2) # Run this in the background as the other function runs
two("World!", 1)
我尝试了协程,但它对我来说并没有真正发挥作用,因为一个在另一个后面运行。
您可以使用多线程让一个函数在后台运行。对于您的情况,您可以将代码更改为如下所示:
import time, threading
def one(msg, a):
time.sleep(a)
print(msg)
def two(msg, a):
time.sleep(a)
print(msg)
thread = threading.Thread(target=one, args=("Hello, ", 2))
thread.start()
two("World!", 1)