# function that will be in a thread
def my_func(msg_queue, stop_event):
while not stop_event.is_set(): # <============= will stop if stop_event is set
msg_queue.put("hi")
sleep(0.1)
stop_event= threading.Event()
p = Thread(target=my_func, args=(msg_queue, stop_event))
p.start()
stop_event.set() # <====== to stop the thread
# how to kill threads
# using set/reset stop flag
import threading
import time
def run():
while True:
print('thread running')
global stop_threads
if stop_threads:
break
stop_threads = False
t1 = threading.Thread(target = run)
t1.start()
time.sleep(1)
stop_threads = True
t1.join()
print('thread killed')