【问题标题】:Is it normal for Tokio to open this many threads/processes?Tokio 开这么多线程/进程正常吗?
【发布时间】:2022-12-04 09:57:25
【问题描述】:

Tokio开这么多线程正常吗?

我所做的就是使用 tokio::net::UnixListener 来监听套接字。但是正如你在top中看到的那样,Tokio 已经打开了 8 个不同的进程/线程,名为tokio-runtime-w

是什么原因造成的,有必要有这么多,可以限制/省略吗?

pub struct StreamServer {
    pub socket: UnixListener,
}

impl StreamServer {
    pub async fn new() -> Result<Self, Box<dyn Error>> {
        let directory = temp_dir();

        let path = directory.as_path().join("d");
        if path.exists() {
            remove_file(&path).await?;
        }

        let socket = UnixListener::bind(&path)?;
        Ok(Self { socket })
    }

    pub async fn run(&mut self) -> Result<(), Box<dyn Error>> {
        loop {
            match &self.socket.accept().await {
                Ok((stream, addr)) => loop {
                    match &self.stream.readable().await {
                        Ok(()) => {
                            let mut buf = Vec::with_capacity(1024);

                            match &self.stream.try_read_buf(&mut buf) {
                                Ok(n) => {
                                    let msg = String::from_utf8((&buf.as_slice()[..*n]).to_vec())?;
                                    Ok((msg, *n))
                                }
                                Err(ref e) if e.kind() == ErrorKind::WouldBlock => {
                                    Ok(("".to_string(), 0))
                                }
                                Err(e) => todo!("{:?}", e),
                            }
                        }
                        Err(e) => todo!("{:?}", e),
                    }
                },
                Err(ref e) if e.kind() == ErrorKind::WouldBlock => {
                    continue;
                }
                Err(_) => todo!(),
            };
        }
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {    
    let mut stream = StreamServer::new().await?;
    stream.run().await?;
}

【问题讨论】:

    标签: asynchronous unix rust rust-cargo rust-tokio


    【解决方案1】:

    是的,这看起来像一个正常的结果。

    有固定数量的worker_threads

    默认值是系统可用的内核数。

    blocking_threads的动态号码:

    默认值为 512。

    您可以使用上面链接的方法配置Runtime,或者worker_threads是可配置的in the attribute,如下所示:

    #[tokio::main(worker_threads = 2)]
    

    【讨论】:

    • 谢谢。如果我设置了 2 个线程,我上面的代码会实际使用它们吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-17
    • 2017-09-24
    • 1970-01-01
    相关资源
    最近更新 更多