1

I have one asynchronous worker function that collects user input from stdin and sends it to other parts of the application. On shut down of the application, I would like to cancel my call to std::io::stdin().read_line(&mut user_input) and return from this function.

I can not get this behavior to work. One of my attempts looks like this:

    #[tokio::test]
    async fn test() -> anyhow::Result<()> {
        let maybe_input_handle = tokio::task::spawn_blocking(|| {
            let mut user_input = String::new();
            match std::io::stdin().read_line(&mut user_input) {
                Ok(_) => Ok(user_input),
                Err(e) => Err(e),
            }
        });
        tokio::time::sleep(Duration::from_secs(1)).await;
        maybe_input_handle.abort();  // I would like the spawned task to be cancelled immediately
        let res = maybe_input_handle.await;
        println!("Result is: {:#?}", res);

        Ok(())
    }

When calling .abort() I would like the future of maybe_input_handle to resolve immediately, but instead on execution I have to press a button first, so that read_line can be resolved. Is there a way to achieve my goal? I considered to programmatically write to stdin in order to cancel the thread, but I could only find out how to write to the standard input of child processes.

MYZ
  • 331
  • 2
  • 10
  • how do you know your program should stop ? – Stargateur Mar 22 '23 at 14:56
  • 1
    Hi. Currently there are two exit conditions. One is via a user input (in this case of course I have no problem because the user "feeds" `read_line()`. The other option is via a network command. Currently, all my other worker tasks stop as I want them to stop (none are performing blocking I/O), I just do not know how to cancel this thread. – MYZ Mar 22 '23 at 15:03
  • 1
    make a select and wait on both stdin and a async task that will tell you to stop, like a broadcast channel. That very similar to a answer I recently updated https://stackoverflow.com/questions/53458755/how-do-i-gracefully-shutdown-the-tokio-runtime-in-response-to-a-sigterm/53505771#53505771 – Stargateur Mar 22 '23 at 15:43
  • Does this answer your question? [Terminating a function after 2 seconds of no stream items](https://stackoverflow.com/questions/75680180/terminating-a-function-after-2-seconds-of-no-stream-items) – drewtato Mar 22 '23 at 18:19
  • Hi. @Stargateur's linked answer helped me to solve this issue. Thank you very much. drewtato thank you for the suggestion. – MYZ Mar 23 '23 at 13:41
  • @MYZ You can self-answer with the previous link and explain exactly what helped you. Helps those coming from Google. – AirOne Jul 06 '23 at 23:00

0 Answers0