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。
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的可调用对象)。
这篇关于线程似乎正在阻塞该进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
织梦狗教程
本文标题为:线程似乎正在阻塞该进程
基础教程推荐
猜你喜欢
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
