Skip to content
Advertisement

Is it the right way to run 2 infiniteloop in python?

i wrote a code in python with 2 infinite loop like this:

import threading 
import time 

ticker = 0

def ticking():
    global ticker
    while True:
        time.sleep(1)
        ticker +=1
        print("ticker = {}".format(ticker))

def main_line():
    while True:
        print("Hello world")
        time.sleep(4)

t1 = threading.Thread(target = ticking)
t2 = threading.Thread(target = main_line)

t1.start()
t2.start()

#t1.join()
if __name__ == "__main__":
    t1.join()
    #t2.join()

If i don’t join any thread it’s not working, but when i join 1 thread, another thread is work too but i don’t know why? Can anyone explain for me?

Advertisement

Answer

Join is used to block the calling method until the thread finishes, throws an exception or time out.

join([timeout]) Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception – or until the optional timeout occurs.

In your case, you have started both threads. So both threads are working. But once you block the main thread by t1.join(), both running threads will be visible.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement