这是因为互斥量没有释放吗?

2023-12-19

我读过这个将我们的单线程服务器变成多线程服务器 https://doc.rust-lang.org/book/ch20-02-multithreaded.html。 并试图去实施它。

我写了这个:

use std::sync::mpsc::{channel, Receiver, Sender};

use std::sync::{Arc, Mutex};

use std::thread;

type task = dyn FnOnce() + Send + 'static;

pub struct Threadpool {
    threads: Vec<thread::JoinHandle<()>>,

    rx: Arc<Mutex<Receiver<Box<task>>>>,

    tx: Sender<Box<task>>,
}

impl Threadpool {
    pub fn new(size: usize) -> Threadpool {
        let mut tasks = Vec::with_capacity(size);

        let (tx, rx): (Sender<Box<task>>, Receiver<Box<task>>) = channel();

        let rx = Arc::new(Mutex::new(rx));

        for _ in 0..size {
            let rx = rx.clone();

            let task = thread::spawn(move || {
                loop {
                   let job= rx.lock().unwrap().recv().unwrap();
                   job();
                }
            });

            tasks.push(task);
        }

        Threadpool {
            threads: tasks,
            rx,
            tx,
        }
    }

    pub fn execute<F>(&self, f: F)
    where
        F: FnOnce() + Send + 'static,
    {
        self.tx.send(Box::new(f)).unwrap();
    }
}

有用。

但当我改变时

let job= rx.lock().unwrap().recv().unwrap();
job();

to

rx.lock().unwrap().recv().unwrap()();

当我打开时localhost:port/sleep,然后打开localhost:port,需要 5 秒。

我在 main 中设置了这个

"GET /sleep HTTP/1.1" => {
            thread::sleep(Duration::from_secs(5));
            ("HTTP/1.1 200 OK", "hello.html")
        }

我已经知道了while let会导致这种情况。

但我不明白为什么我上面的代码也会导致这种情况。

有谁能给我答案吗。


在 Rust 中,临时对象被删除在包含它们的表达式的末尾(带有一些caveats https://rustwiki.org/en/reference/destructors.html#temporary-scopes此处不相关)。

我们感兴趣的临时对象是互斥体的守卫,其drop负责释放互斥锁。

所以,写下drop明确地,你的第一个代码:

let job = rx.lock().unwrap().recv().unwrap();
job();

相当于:

let mut guard = rx.lock().unwrap();
let job = guard.recv().unwrap();
drop(guard);
job();

你的第二个代码:

rx.lock().unwrap().recv().unwrap()();

相当于:

let mut guard = rx.lock().unwrap();
let job = guard.recv().unwrap()
job();
drop(guard);

如您所见,现在您正在调用job()互斥体仍处于锁定状态的函数。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

这是因为互斥量没有释放吗? 的相关文章

随机推荐