summaryrefslogtreecommitdiffstats
path: root/tokio/src/executor/thread_pool/shutdown.rs
blob: 40d8f04ac80e56dc8abf4b2ae9371a348db6dd2b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
//! A shutdown channel.
//!
//! Each worker holds the `Sender` half. When all the `Sender` halves are
//! dropped, the `Receiver` receives a notification.

use crate::executor::loom::sync::Arc;

use tokio_sync::oneshot;

#[derive(Debug, Clone)]
pub(super) struct Sender {
    tx: Arc<oneshot::Sender<()>>,
}

#[derive(Debug)]
pub(super) struct Receiver {
    rx: oneshot::Receiver<()>,
}

pub(super) fn channel() -> (Sender, Receiver) {
    let (tx, rx) = oneshot::channel();
    let tx = Sender { tx: Arc::new(tx) };
    let rx = Receiver { rx };

    (tx, rx)
}

impl Receiver {
    /// Block the current thread until all `Sender` handles drop.
    pub(crate) fn wait(&mut self) {
        use crate::executor::enter;

        let mut e = match enter() {
            Ok(e) => e,
            Err(_) => {
                if std::thread::panicking() {
                    // Already panicking, avoid a double panic
                    return;
                } else {
                    panic!("cannot block on shutdown from the Tokio runtime");
                }
            }
        };

        // The oneshot completes with an Err
        let _ = e.block_on(&mut self.rx);
    }
}