summaryrefslogtreecommitdiffstats
path: root/tokio/src/runtime/thread_pool/shutdown.rs
blob: 414c1c84ab10c592c2bb876808f792bfbe9adef8 (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
//! A shutdown channel.
//!
//! Each worker holds the `Sender` half. When all the `Sender` halves are
//! dropped, the `Receiver` receives a notification.

use crate::loom::sync::Arc;
use crate::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 {
    /// Blocks the current thread until all `Sender` handles drop.
    pub(crate) fn wait(&mut self) {
        use crate::runtime::enter::{enter, try_enter};

        let mut e = if std::thread::panicking() {
            match try_enter() {
                Some(enter) => enter,
                _ => return,
            }
        } else {
            enter()
        };

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