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的可调用对象)。
这篇关于线程似乎正在阻塞该进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
编程基础网
本文标题为:线程似乎正在阻塞该进程
基础教程推荐
猜你喜欢
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
