What is the correct way in Rust to create a timeout for a thread or a function?

Viewed 11835

This is my code:

use std::net;
use std::thread;

fn scan_port(host: &str, port: u16) -> bool {
    let host = host.to_string();
    let port = port;
    let t = thread::spawn(move || net::TcpStream::connect((host.as_str(), port)).is_ok());

    t.join().unwrap()
}

How do I create a situation where the thread will be terminated or killed if the connection didn't finish in N seconds?

The reason for all of this is that Rust has no way to set a socket connection timeout so I have no way to ensure the program won't get stuck.

2 Answers
Related