简体   繁体   中英

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.

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()

Your parentheses are in the wrong places in the first version.

As currently written, you are passing the result of calling thread1 when creating t1 ; since that call never returns, you never actually create a thread. So you need to remove those parentheses.

But you don't include the parentheses where you are trying to call the start and join methods, so the threads never actually got started even when you didn't use the extra parentheses when creating the threads.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM