0

I am trying to start a thread to listen to the incoming messages from a socket. so it contains an infinite loop. but when I try to close the gui, it hangs there, and does not close it. here is more simplified code without using any gui.

import threading,time,sys

def f(x):
    while True:
        time.sleep(0.5)
        print(x)
timer = threading.Timer(0.1,f,("some text",) )
timer.start()
time.sleep(2)
print("time to stop")
sys.exit()

as you see the line sys.exit() won't end all threads (main thread and thread started by timer). now I was wondering how to kill that specific thread which started by the timer. thank you for your help

Shoaib Mirzaei
  • 512
  • 4
  • 11

1 Answers1

0

I finally find a solution for it. somehow we can use global variables to end an endless loop inside a thread, and therefore close it.

import threading,time

def f(x):
    global z
    while True:
        time.sleep(0.5)
        print(x)
        if not z:
            break
            
global z
z = True
timer = threading.Timer(0.1,f,("some text",) )
timer.start()
time.sleep(2)
print("time to stop")
z = False
Shoaib Mirzaei
  • 512
  • 4
  • 11