线程似乎正在阻塞该进程
问题描述
class MyClass():
def __init__(self):
...
def start(self):
colorThread = threading.Thread(target = self.colorIndicator())
colorThread.start()
while True:
print ('something')
...
...
我还在colorIndicator()中有一个print语句。这份声明正在打印出来。但start()方法的While循环内的print语句未显示在屏幕上。
colorIndicator()也有一个无限循环。它从互联网上获取一些数据,并更新一个计数器。此计数器在__init__中初始化为self变量,我正在其他方法中使用该变量。
我不明白为什么没有执行内部print。
ColorIndicator函数:
def colorIndicator(self):
print ('something else')
...
while (True):
...
print ('here')
time.sleep(25)
我得到的输出如下:
something else
here
here
那之后我就停了。因此,ColorIndicator显然正在完全运行。
我使用import在一个python解释器中(在一个终端中)调用该脚本。然后我实例化MyClass并调用start函数。
解决方案
您实际上没有在线程中运行colorIndicator,因为您在主线程中调用了,而不是将方法本身(未调用)作为线程target传递。更改:
colorThread = threading.Thread(target=self.colorIndicator())
# ^^ Agh! Call parens!
收件人:
# Remove parens so you pass the method, without calling it
colorThread = threading.Thread(target=self.colorIndicator)
# ^ Note: No call parens
基本上,您的问题在于,在构造Thread之前,它试图运行colorIndicator直到完成,以便它可以使用其返回值作为target,这在许多方面都是错误的(该方法永远不会返回,即使它返回了,也不会返回适合用作target的可调用对象)。
相关文章