2

I have a thread that reads from and sends to a TcpStream. I want to be able to send a message to the thread that will then write it to the stream.

I want this pseudocode:

pub fn spawn_thread(mut stream: TcpStream, commands: Receiver<String>) {
    std::thread::spawn(move || loop {
        // wait for either tcp data or command
        if /* got command */ {
            handle_write(/* ... */);
        } else if /* got tcp data */ {
            handle_read(/* ... */);
        }
    });
}

How would I go about doing this, or am I thinking about it wrong? I'm pretty new to Rust, coming from more of a C/C++ background. I'd think of using a select statement here. Is there any Rust equivalent?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Ben Jilks
  • 21
  • 1
  • 1
    Welcome to Stack Overflow! Your question might be answered by the answers of [What is the standard way to get a Rust thread out of blocking operations?](https://stackoverflow.com/q/52465480/155423). If not, please **[edit]** your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Feb 15 '21 at 18:28
  • Dunno about rust but, in other languages, I would have used two threads, one receiving, one waiting on a producer-consumer queue for data to send, (must try some rust - another longtime user suggested it:) – Martin James Feb 15 '21 at 18:33
  • Looking at the documentation, it seems like [`set_nonblocking`](https://doc.rust-lang.org/std/net/struct.TcpStream.html#method.set_nonblocking) could be used to do this. – apilat Feb 15 '21 at 19:37

0 Answers0