How can I stop reading from a tokio::io::lines stream?

前端 未结 2 1504
温柔的废话
温柔的废话 2020-12-21 10:45

I want to terminate reading from a tokio::io::lines stream. I merged it with a oneshot future and terminated it, but tokio::run was st

相关标签:
2条回答
  • 2020-12-21 11:07

    There's nothing wrong with your strategy, but it will only work with futures that don't execute a blocking operation via Tokio's blocking (the traditional kind of blocking should never be done inside a future).

    You can test this by replacing the tokio::io::lines(..) future with a simple interval future:

    let lines = Interval::new(Instant::now(), Duration::from_secs(1));
    

    The problem is that tokio::io::Stdin internally uses tokio_threadpool::blocking .

    When you use Tokio thread pool blocking (emphasis mine):

    NB: The entire task that called blocking is blocked whenever the supplied closure blocks, even if you have used future combinators such as select - the other futures in this task will not make progress until the closure returns. If this is not desired, ensure that blocking runs in its own task (e.g. using futures::sync::oneshot::spawn).

    Since this will block every other future in the combinator, your Receiver will not be able to get a signal from the Senderuntil the blocking ends.

    Please see How can I read non-blocking from stdin? or you can use tokio-stdin-stdout, which creates a channel to consume data from stdin thread. It also has a line-by-line example.

    0 讨论(0)
  • 2020-12-21 11:12

    Thank you for your comment and correcting my sentences.

    I tried to stop this non-blocking Future and succeeded.

    let lines = Interval::new(Instant::now(), Duration::from_secs(1));
    

    My understating is that it would work for this case to wrap the blocking Future with tokio threadpool::blocking. I'll try it later.

    Thank you very much.

    0 讨论(0)
提交回复
热议问题