Search code examples
pythonmultithreadingpython-multithreading

Python threading stopping code from being executed


I have this code here:

from threading import Thread
import time

class TestClass():

    def __init__ (self, name):
        self.name = name

        self.thread = Thread(target=self.run())
        
        self.thread.start()

    def run(self):
        while True:
            print(self.name)

            time.sleep(1)

test = TestClass('word')

print('done')

So basically this just keeps printing 'word', without it ever printing 'done' . This is a small demonstration of the problem I'm having, cause threading is getting stuck and it's stopping other lines of code from being executed. You can try this on your own and you will get same results. Is anything I'm missing here?


Solution

  • That should work and is the recommended way to use the Thread class.

    from threading import Thread
    import time
    
    class TestClass(Thread):
    
        def __init__ (self, name):
            super().__init__()
            self.name = name
            self.start()
    
        def run(self):
            while True:
                print(self.name)
    
                time.sleep(1)
    
    test = TestClass('word')
    
    print('done')