[英]Run two function concurrently
我定义了几个函数。
def func1():
'''something goes here'''
def func2():
'''something goes here'''
def func3():
'''something goes here'''
def func4():
'''something goes here'''
所以问题是:如果我们在func1()
运行时调用该函数,我想始终运行func1()
并且其他函数( func2()
、 func3()
、 func4()
)应该可用。 除非用户调用,否则我不希望func2()
、 func3()
、 func4()
运行。 这怎么办?。 这是我到目前为止所做的
if __name__ == '__main__':
Thread(target=func1()).start()
在这里,我启动了函数func1()
。 意思是当函数func1()
运行时,如果用户调用它应该运行的其他函数,否则不会
我已经提到了一些线程和多处理,但仍然无法得到答案。 是否可以? 如果是这样,请以正确的方式指导我。
提前致谢
threading.Timer 应该可以解决问题:
from threading import Timer
def func1():
t = Timer(60.0, func2)
t.start() #func2 will be called 60 seconds from now.
def func2():
'''something goes here'''
def func3():
'''something goes here'''
def func4():
'''something goes here'''
根据您指定的内容,这是代码。 func1()
由线程执行,并且一直在执行。 用户指定的输入触发其余功能。
from threading import Thread
def func1():
'''do something'''
func1() #recursive call to keep it running
def func2():
'''something goes here'''
def func3():
'''something goes here'''
def func4():
'''something goes here'''
if __name__ == '__main__':
Thread(target=func1).start()
while True:
n = input("Enter Command: ")
if n=="func2":
func2()
elif n=="func3":
func3()
# add your cases
else:
print("Invalid Input")
您的代码中的一个明显错误是启动您需要的线程
Thread(target=func1).start()
即目标应该引用函数而不是调用它(不是func1()
)。 所以代码应该是:
from threading import Thread
import time
def func1():
while True:
print('Running func1')
time.sleep(60)
def func2():
'''something goes here'''
print('func2 called')
def func3():
'''something goes here'''
print('func3 called')
def func4():
'''something goes here'''
print('func4 called')
if __name__ == '__main__':
Thread(target=func1).start()
func2()
func3()
func4()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.