How can I kill all threads?

Sperly1987 picture Sperly1987 · Sep 8, 2016 · Viewed 9.6k times · Source

In this script:

import threading, socket    

class send(threading.Thread):

    def run(self):
        try:
            while True:
                try:
                    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                    s.connect((url,port))
                    s.send(b"Hello world!")
                    print ("Request Sent!")
                except:
                    s.close()
        except KeyboardInterrupt:
            # here i'd like to kill all threads if possible

for x in range(800):
    send().start()  

Is it possible to kill all threads in the except of KeyboardInterrupt? I've searched on the net and yeah, I know that it has been already asked, but I'm really new in python and I didn't get so well the method of these other question asked on stack.

Answer

ShadowRanger picture ShadowRanger · Sep 8, 2016

No. Individual threads can't be terminated forcibly (it's unsafe, since it could leave locks held, leading to deadlocks, among other things).

Two ways to do something like this would be to either:

  1. Have all threads launched as daemon threads, with the main thread waiting on an Event/Condition and exiting as soon as one of the threads sets the Event or notifies the Condition. The process terminates as soon as the (sole) non-daemon thread exits, ending all the daemon threads
  2. Use a shared Event that all the threads poll intermittently, so they cooperatively exit shortly after it is set.