1

When I press CTRL+C to interrupt program it quits only main thread and new created still working. How to terminate all threads?

import threading, time

def loop():
    while True:
        print("maked thread")
        time.sleep(1)

t = threading.Thread(target = loop)
t.start()

while True:
    print("loop")
    time.sleep(1)

1 Answers1

2

You can use use a flag and have the thread check the flag for exit, while in the main thread you should catch the KeyboardInterrupt exception and set the flag.

import threading, time
import sys

stop = False

def loop():
    while not stop:
        print("maked thread")
        time.sleep(1)
    print('exiting thread')

t = threading.Thread(target = loop)
t.start()

try:
    while True:
        print("loop")
        time.sleep(1)
except KeyboardInterrupt:
    stop = True
    sys.exit()
blhsing
  • 91,368
  • 6
  • 71
  • 106