How can I kill all threads?
<p>In this script:</p>

<pre><code>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()  
</code></pre>

<p>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.</p>

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

<p>Two ways to do something like this would be to either:</p>

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

python multithreading python-3.x kill terminate