同时运行两个函数

2024-06-28 11:42:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我定义了几个函数

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())应该是可用的I除非用户调用,否则不要运行func2()func3()func4()。如何做到这一点?。 这是我到目前为止所做的

if __name__ == '__main__':
    Thread(target=func1()).start()

在这里,我启动了函数func1()。意思是当函数func1()运行时,如果用户调用其他函数,则它应该运行,否则不会运行

我提到了一些线程和多处理,但仍然无法得到答案。可能吗?如果是这样,请以正确的方式指导我

提前谢谢


Tags: 函数用户nameifhere定义maindef
3条回答

假设您正在Python交互控制台中执行此操作。如果您这样做:

from threading import Timer

def func2(): 
    print("func2 called")

def func1(): 
    print("func1 called")

t = Timer(60.0, func2)
t.start()

现在控制台是自由的,并显示提示符func2将在60.0秒后执行,您可以调用func1()或任何您想要的。看:

enter image description here

线程。计时器应执行以下操作:

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'''

代码中一个明显的错误是启动所需的线程

Thread(target=func1).start()

也就是说,target应该引用函数而不是调用它(NOT 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()

相关问题 更多 >