Thread seems to be blocking the process

2019-08-17 17:22发布

问题:

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

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

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

I also have a print statement inside the colorIndicator(). That statement is getting printed. But the print statement inside the while loop of start() method isn't displayed on screen.

The colorIndicator() also has an infinite loop. It gets some data from the internet and updates a counter. This counter is initialized inside __init__ as self variable and I'm using that variable inside other methods.

I do not understand why print inside while is not being executed.

colorIndicator function:

def colorIndicator(self):
        print ('something else')
        ...
        while (True):
            ...
            print ('here')
        time.sleep(25)

The output I get is the following:

something else
here
here

I stopped it after that. So, the colorIndicator is clearly running completely. I'm calling the script with import in a python interpreter (in a terminal). Then I instantiate MyClass and call the start function.

回答1:

You're not actually running colorIndicator in a thread, because you called it in the main thread, rather than passing the method itself (uncalled) as the thread target. Change:

    colorThread = threading.Thread(target=self.colorIndicator())
    #                                                        ^^ Agh! Call parens!

to:

    # Remove parens so you pass the method, without calling it
    colorThread = threading.Thread(target=self.colorIndicator)
    #                                                        ^ Note: No call parens

Basically, your problem is that before you ever construct the Thread, it's trying to run colorIndicator to completion so it can use its return value as the target, which is wrong in multiple ways (the method never returns, and even if it did, it wouldn't return a callable suitable for use as a target).