在Python 2中线程化无尽的while循环

s4w*_*0ff 1 python multithreading python-2.7

我不确定为什么这行不通。该线程在定义后立即启动,似乎不在实际线程中……也许我丢失了一些东西。

import threading
import time

def endless_loop1():
    while True:
        print('EndlessLoop1:'+str(time.time()))
        time.sleep(2)

def endless_loop2():
    while True:
        print('EndlessLoop2:'+str(time.time()))
        time.sleep(1)

print('Here1')
t1 = threading.Thread(name='t1', target=endless_loop1(), daemon=True)
print('Here2')
t2 = threading.Thread(name='t2', target=endless_loop2(), daemon=True)
print('Here3')
t1.start()
print('Here4')
t2.start()
Run Code Online (Sandbox Code Playgroud)

输出:

Here1
EndlessLoop1:1446675282.8
EndlessLoop1:1446675284.8
EndlessLoop1:1446675286.81
Run Code Online (Sandbox Code Playgroud)

tza*_*man 5

您需要提供target=一个可调用对象

target=endless_loop1()
Run Code Online (Sandbox Code Playgroud)

在这里,您实际上是在调用 endless_loop1(),因此它会立即在您的主线程中执行。您想要做的是:

target=endless_loop1
Run Code Online (Sandbox Code Playgroud)

它将您Thread的函数对象传递给它,以便它本身可以调用它。

另外,daemon它实际上不是init参数,您需要在调用之前分别设置它start

t1 = threading.Thread(name='t1', target=endless_loop1)
t1.daemon = True
Run Code Online (Sandbox Code Playgroud)