线程似乎阻止了进程

时间:2017-08-23 03:23:38

标签: python python-3.x python-multithreading

class MyClass():
    def __init__(self):
        ...

    def start(self):
        colorThread = threading.Thread(target = self.colorIndicator())
        colorThread.start() 

        while True:
            print ('something')
            ...
            ...

我在print内也有一个colorIndicator()声明。该声明正在印刷。但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显然完全运行。 我在python解释器中(在终端中)使用import调用脚本。然后我实例化MyClass并调用start函数。

1 个答案:

答案 0 :(得分:2)

你实际上并没有在一个线程中运行colorIndicator,因为你在主线程中调用它,而不是将方法本身(未调用)作为线程{{1}传递}。变化:

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的callable。)

相关问题