As @Shepmaster noted: this is a bad idea to stop streams.
Instead, you should give the Sender
thread through which it should notify you if it successfully opened the connection (perhaps even sending you a hilt). Then you can leave your main sleep
thread at the expected time. When your thread wakes up, it checks the appropriate Receiver
for some signs of life from the thread. If the thread did not respond, just release it into the wild by discarding JoinHandle
and Receiver
. This is not like when it consumes CPU time (it is locked) and it does not consume too much memory. If it is ever unlocked, it will find that Sender
not connected and can be disconnected forever.
Of course, you should not have bazillions of these open threads, because they still use resources (memory and system thread descriptors), but on a regular system, which is not a big problem.
Example:
use std::net; use std::thread; use std::sync::mpsc; fn scan_port(host: &str, port: u16) -> bool { let host = host.to_string(); let port = port; let (sender, receiver) = mpsc::channel(); let t = thread::spawn(move || { match sender.send(net::TcpStream::connect((host.as_str(), port))) { Ok(()) => {},
source share