线程,并行“ while True”循环

我知道这个问题被问过很多次,但是我无法使它正常工作。 我有两个单独的函数,都使用 while True 循环:

def function_1():
    while True:
        #do something

def function_2():
    while True:
        #do something also

我尝试使用 threading 这样运行它们:

t_1 = threading.Thread(target=function_1(),args=())
t_2 = threading.Thread(target=function_2(),args=())

t_1.start()
t_2.start()

问题在于它仅执行第一个。我也尝试将其包装到函数中并调用它,但结果相似。 有提示吗?

hoho1141 回答:线程,并行“ while True”循环

t_1 = threading.Thread(target=function_1)
t_2 = threading.Thread(target=function_2)

将功能传递给目标时,您必须卸下括号。在Python中,可以将函数视为对象,这就是为什么可以实现的原因

在放入括号时,python本质上会等待function_1()返回另一个函数,但这种情况并未发生。因此,由于function_1是一段时间的True函数,因此当您启动线程1时,它就卡在了那里。

阅读? functions are first class objects - Dan Bader

本文链接:https://www.f2er.com/3139439.html

大家都在问