Search code examples
pythonmultithreadingpython-multithreading

How to run infinite loops within threading in python


I've looked everywhere and it seems like the threads I write should work. I've checked many other threads about it and tutorials. I can't seem to run infinite loops in threads. Despite what I do, only the first thread works/prints.

Here is the code for just methods.

import threading


def thread1():
      while True:
            print("abc")
def thread2():
      while True:
            print ("123")

if __name__ == "__main__":
    t1 = threading.Thread(target=thread1())
    t2 = threading.Thread(target=thread2())

    t1.start
    t2.start

    t1.join
    t2.join

Removing the prentheses at the end of calling the functions with target=causes nothing to print so I keep that in there.

Here is the class/object version.

from threading import Thread
class Thread1(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.daemon = True
        self.start

    def run():
        while True:
            print ("abc")

class Thread2(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.daemon = True
        self.start

    def run():
        while True:
            print ("123")

Thread1.run()
Thread2.run()

both never get to printing 123 and I can't figure out why. It looks like infinite loops shouldn't be an issue because they are being run in parallel. I tried time.sleep (bc maybe the GIL stopped it idk) so thread2 could run while thread1 was idle. Didn't work.


Solution

  • For the first example:

    if __name__ == "__main__":
        t1 = threading.Thread(target=thread1)
        t2 = threading.Thread(target=thread2)
    
        t1.start()
        t2.start()
    
        t1.join()
        t2.join()
    

    Pass the function, not the result of calling the function, to threading.Thread as its target.

    For the section example. Don't call run. Call start. After creating an instance.

    from threading import Thread
    class Thread1(Thread):
        def __init__(self):
            Thread.__init__(self)
            self.daemon = True
    
        def run():
            while True:
                print ("abc")
    
    class Thread2(Thread):
        def __init__(self):
            Thread.__init__(self)
            self.daemon = True
    
        def run():
            while True:
                print ("123")
    
    Thread1().start()
    Thread2().start()