线程似乎阻塞了进程
Thread seems to be blocking the process
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
里面的while没有被执行。
colorIndicator 函数:
def colorIndicator(self):
print ('something else')
...
while (True):
...
print ('here')
time.sleep(25)
我得到的输出如下:
something else
here
here
之后我停止了它。因此,colorIndicator 显然完全 运行。
我在 python 解释器(在终端中)中用 import
调用脚本。然后我实例化 MyClass
并调用 start
函数。
您实际上并没有在线程中 运行ning 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
完成,因此它可以使用其 return 值作为target
,这在多个方面都是错误的(该方法从来没有 returns,即使它这样做了,它也不会 return 一个适合用作 target
的可调用对象).
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
里面的while没有被执行。
colorIndicator 函数:
def colorIndicator(self):
print ('something else')
...
while (True):
...
print ('here')
time.sleep(25)
我得到的输出如下:
something else
here
here
之后我停止了它。因此,colorIndicator 显然完全 运行。
我在 python 解释器(在终端中)中用 import
调用脚本。然后我实例化 MyClass
并调用 start
函数。
您实际上并没有在线程中 运行ning 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
完成,因此它可以使用其 return 值作为target
,这在多个方面都是错误的(该方法从来没有 returns,即使它这样做了,它也不会 return 一个适合用作 target
的可调用对象).