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
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
//! RAII guard used to notify child tasks that the parent has been dropped.

use std::future::Future;
use tokio::sync::watch::{channel, Receiver, Sender};

#[derive(Debug)]
pub struct SpawnScope {
    tx: Option<Sender<()>>,
    rx: Receiver<()>,
}

impl SpawnScope {
    pub fn new() -> Self {
        let (tx, rx) = channel(());
        Self { tx: Some(tx), rx }
    }

    pub fn handle(&self) -> SpawnScopeHandle {
        let rx = self.rx.clone();
        SpawnScopeHandle(rx)
    }

    pub fn spawn<F>(&self, future: F) 
    where F: Future<Output = ()> + Send + 'static
    {
        let mut handle = self.handle();
        tokio::spawn(async move {
            tokio::select! {
                _ = handle.left() => {},
                _ = future => {},
            }
        });
    }

    pub fn close(&mut self) {
        self.tx.take();
    }
}

#[derive(Debug)]
pub struct SpawnScopeHandle(Receiver<()>);

impl Clone for SpawnScopeHandle {
    fn clone(&self) -> Self {
        let rx = self.0.clone();
        SpawnScopeHandle(rx)
    }
}

impl SpawnScopeHandle {
    pub async fn left(&mut self) {
        while let Some(_) = self.0.recv().await {}
    }


    pub fn spawn<F>(&self, future: F) 
    where F: Future<Output = ()> + Send + 'static
    {
        let mut handle = self.clone();
        tokio::spawn(async move {
            tokio::select! {
                _ = handle.left() => {},
                _ = future => {},
            }
        });
    }
}

#[tokio::test]
async fn test_drop() {
    use std::future::Future;
    use std::time::Duration;
    use tokio::time::delay_for;
    let scope = SpawnScope::new();

    fn get_task(mut scope: SpawnScopeHandle) -> impl Future<Output = i32> {
        async move {
            let mut n = 0;
            loop {
                tokio::select! {
                  _ = scope.left() => {
                    return n
                  }
                  _ = delay_for(Duration::from_millis(50)) => {
                    n = n + 1
                  }
                }
            }
        }
    }

    let t1 = tokio::spawn(get_task(scope.handle()));
    let t2 = tokio::spawn(get_task(scope.handle()));
    let t3 = tokio::spawn(get_task(scope.handle()));

    delay_for(Duration::from_millis(100)).await;
    drop(scope);

    let (v1, v2, v3) = tokio::try_join!(t1, t2, t3).unwrap();
    assert!(v1 > 0);
    assert!(v2 > 0);
    assert!(v3 > 0);
}

#[tokio::test]
async fn test_spawn() {
    use tokio::sync::oneshot::*;
    
    let (tx, rx) = channel();

    struct Guard(Option<Sender<()>>);
    impl Drop for Guard {
        fn drop(&mut self) {
            self.0.take().unwrap().send(()).ok();
        }
    }

    let g = Guard(tx.into());
    let scope = SpawnScope::new();

    scope.spawn(async move {
        futures::future::pending::<()>().await;
        drop(g)
    });

    drop(scope);

    rx.await.unwrap();
}