2

I have 2 threads in my program that I wish to stop on keyboard interrupt but I dont know how to do it. One of the threads has a while loop and the other is just a function which calls a class full of functions. Please help thank you.

Stopping the program

  • You can use a thread to wait for the user to input some value to break the threads. Look at [How to stop a thread in Python](https://www.pythontutorial.net/python-concurrency/python-stop-thread/). – Alias Cartellano Apr 10 '23 at 17:53
  • I made [some code](https://textdoc.co/1pjxQGsSLmtAKdIZ) to demonstrate how this can be done. It's based on the link I used in my comment above. – Alias Cartellano Apr 11 '23 at 02:04
  • Thank you very much for your response, it worked perfectly fine with two threads but with the other thread its not working, when i type exit its stops two and starts the other. Can i put 3 threads in that please? Thank you – Andrea Gatt Apr 11 '23 at 14:36

3 Answers3

1

it's simple you have only to kill thread

#Start a new thread
t = multiprocessing.Process(target = func)
t.start()
#Kill the thread
t.kill()
Xavier
  • 11
  • 1
  • Hello and thank you for your response, currently I am using the threadding module not the processing module, but i still tried it and when i ran the program it said would you like to kill the program – Andrea Gatt Apr 10 '23 at 18:42
1

You can use KeyboardInterrupt to catch CTRL+C input and do kill threads.

t = None
try:
    t = multiprocessing.Process(target = func)
    t.start()
except KeyboardInterrupt:
    t.kill()
    print("stopping")
  • Hello and thank you for your response, I have just tried that right now and the program automatically says "Your program is still Running! Do you want to kill it?" exactly when I press the run button – Andrea Gatt Apr 10 '23 at 18:57
  • @AndreaGatt does [this](https://stackoverflow.com/questions/46039560/using-quit-exit-etc-says-the-program-is-still-running-do-you-want-to-ki) help? – digital_monk Apr 11 '23 at 12:10
0

I am using this logic for standard thread canceling:

1. MainThread

  • I run input from keyboard in main process/thread
  • I can setup event via threading.Event().set()
  • See code sample for class MainThread(threading.Thread)
def __init__(self,  *args, **kwargs):
    super(StoppableThread, self).__init__(*args, **kwargs)
    self._stop_event = threading.Event()

def stop(self):
    self._stop_event.set()

def stopped(self):
    return self._stop_event.is_set()

2. BackgroudThreads

  • Background threads are checking (periodically) this signal state and can close their execution.

BTW: nice clarification see article

JIST
  • 1,139
  • 2
  • 8
  • 30