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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
use std::sync::{Arc, Mutex, Condvar};
use std::ops::{Deref, DerefMut};

#[derive(Clone)]
pub struct Value<T> where T: Send + Sync + Clone {
    value: Option<T>,
    pool: BlockingObjectPool<T>,
}

impl<T> Drop for Value<T> where T: Send + Sync + Clone {
    fn drop(&mut self) {
        let value = self.value.take().unwrap();
//        println!("pushing back...");
        self.pool.put(value);
    }
}

impl<T> AsRef<T> for Value<T> where T: Send + Sync + Clone {
    fn as_ref(&self) -> &T {
        self.value.as_ref().unwrap()
    }
}

impl<T> AsMut<T> for Value<T> where T: Send + Sync + Clone {
    fn as_mut(&mut self) -> &mut T {
        self.value.as_mut().unwrap()
    }
}

impl<T> Deref for Value<T> where T: Send + Sync + Clone {
    type Target = T;

    #[inline]
    fn deref(&self) -> &T {
        self.as_ref()
    }
}

impl<T> DerefMut for Value<T> where T: Send + Sync + Clone {
    #[inline]
    fn deref_mut(&mut self) -> &mut T {
        self.as_mut()
    }
}

#[derive(Clone)]
pub struct BlockingObjectPool<T> where T: Send + Sync + Clone {
    guard: Arc<(Mutex<Vec<T>>, Condvar)>,
}

impl<T> BlockingObjectPool<T> where T: Send + Sync + Clone {
    pub fn with_objects(objects: Vec<T>) -> Self {
        BlockingObjectPool {
            guard: Arc::new((Mutex::new(objects), Condvar::new())),
        }
    }

    pub fn with_capacity(pool_size: usize, builder: fn() -> T) -> Self {
        let items: Vec<T> = (0..pool_size).map(|_| builder()).collect();
        Self::with_objects(items)
    }

    pub fn get(&self) -> Value<T> {
        let &(ref lock, ref condvar) = &*self.guard;
        let mut items = lock.lock().unwrap();
        let mut item = items.pop();
        while item.is_none() {
            items = condvar.wait(items).unwrap();
            item = items.pop();
        }

        let item = item.unwrap();
        Value {
            value: Some(item),
            pool: self.clone(),
        }
    }

    fn put(&mut self, item: T) {
        let &(ref lock, ref condvar) = &*self.guard;
        let mut items = lock.lock().unwrap();
        items.push(item);
        condvar.notify_one();
    }
}


#[cfg(test)]
mod tests {
    use super::*;
    use std::thread::*;
    use std::time::Duration;

    #[test]
    fn test1() {
        #[derive(Clone)]
        struct Hello {
            a: i32,
            b: i32,
        }

//        impl Drop for M1 {
//            fn drop(&mut self) {
//                println!("on drop!");
//            }
//        }

        let pool = BlockingObjectPool::with_capacity(2, || Hello { a: 1, b: 2 });
        let pool1 = pool.clone();
        let t1 = spawn(move || {
            let mut m = pool.get();
            m.a = 11;
            m.b = 22;
            drop(m);

            sleep(Duration::from_millis(20));

            //the following line will be blocked util t2 thread is finished.
            let m = pool.get();
            assert_eq!(m.a, 111);
            println!("expect(2). t1:m.a={},m.b={}", m.a, m.b);
            let _m = pool.get();
            println!("expect(3). t1 will sleep 2 seconds");
            sleep(Duration::from_secs(2));
            println!("expect(4). t1 finished");
        });
        let t2 = spawn(move || {
            sleep(Duration::from_millis(10));
            let mut m = pool1.get();
            assert_eq!(m.a, 11);
            println!("expect(1). t2(1):m.a={},m.b={}", m.a, m.b);
            m.a = 111;
            m.b = 222;
            drop(m);
            sleep(Duration::from_millis(20));
            let m = pool1.get();
            assert_eq!(m.a, 111);
            println!("expect(5). t2(2):m.a={},m.b={}", m.a, m.b);
        });
        t1.join().unwrap();
        t2.join().unwrap();
    }
}