Python - How can I close / stop threads safely?

I'm making a port scanner for fun, not to be used in practice, since nmap is far, far better than anything I can make.

But I'm having an issue with multithreading. The scanner sends data, gets data back, but I'm looking for a way to close a thread once the data is received.

Currently, I use a timeout method, but that's not really the fastest or most efficient way, because a thread doesn't need to hang open for 1 second or even a half of a second, when the data was already received 0.8 seconds ago and the thread is no longer being used and is not needed.

I'd like to find a way to close those threads that are no longer needed because I'm hitting the thread limit and it'll make the whole loop run faster if I can trim the fat once I'm done with it.

It currently scans 25565 ports in 27 seconds on my machine, with a timeout specifically tuned for my system. But that doesn't mean it would work on other systems.


Stack overflow has multiple answers roughly amounting to, "it's not safe to close threads!"

But what I'm wondering is, is it safe to close the thread considering I can guarantee that it's completely stagnant, not being used, and it's task has been completed?

I could just have some kind of flag like "if data received does not equal null, close thread". Is that still considered unsafe?

By @alldogarepuppy on Tue 25 Apr 2017 |


Offer your help. Be nice!

Login to leave a response!