线程似乎正在阻塞该进程 [英] Thread seems to be blocking the process

查看:10
本文介绍了线程似乎正在阻塞该进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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的可调用对象)。

这篇关于线程似乎正在阻塞该进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆