Stdin::lock 在什么情况下有用?

109*_*149 1 stdin rust

Stdin::lock:

pub fn lock(&self) -> StdinLock<'_>
Run Code Online (Sandbox Code Playgroud)

这在什么情况下有用?

She*_*ter 6

文件指出,我的重点是:

进程的标准输入流的句柄。

每个句柄都是对此进程的输入数据的全局缓冲区的共享引用。可以使用句柄lock来获得对BufRead方法的完全访问权限(例如,.lines()。否则,对该句柄的读取将相对于其他读取被锁定。

use std::io::{self, prelude::*};

fn main() {
    let stdin = io::stdin();
    
    dbg!(stdin.lines().count()); // fails!
    
    let stdin = stdin.lock();
    dbg!(stdin.lines().count());
}
Run Code Online (Sandbox Code Playgroud)
error[E0599]: no method named `lines` found for struct `std::io::Stdin` in the current scope
   --> src/main.rs:6:16
    |
6   |       dbg!(stdin.lines().count());
    |                  ^^^^^ method not found in `std::io::Stdin`
    |
    = note: the method `lines` exists but the following trait bounds were not satisfied:
            `std::io::Stdin: std::io::BufRead`
            which is required by `&mut std::io::Stdin: std::io::BufRead`
Run Code Online (Sandbox Code Playgroud)

  • 在单线程程序中,没有区别。在多线程程序中,如果不使用“lock”,另一个线程可能会拦截某些行。 (9认同)