Issue
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.
Solution
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:
- Have all threads launched as
daemon
threads, with the main thread waiting on anEvent
/Condition
and exiting as soon as one of the threads sets theEvent
or notifies theCondition
. The process terminates as soon as the (sole) non-daemon
thread exits, ending all thedaemon
threads - Use a shared
Event
that all the threads poll intermittently, so they cooperatively exit shortly after it is set.
Answered By - ShadowRanger
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.