1use async_std::sync::{Condvar, Mutex};
2
3#[derive(Debug)]
4pub struct Pool<T> {
5 sync_tuple: Mutex<(Vec<T>, usize)>,
6 cvar: Condvar,
7 max: usize,
8}
9
10impl<T> Pool<T> {
11 pub fn new(max: usize) -> Self {
12 Self {
13 sync_tuple: Mutex::new((Vec::new(), 0)),
14 cvar: Condvar::new(),
15 max,
16 }
17 }
18
19 pub async fn put(&self, item: T) {
20 let mut lock_guard = (&self.sync_tuple).lock().await;
21 (*lock_guard).0.push(item);
22 self.cvar.notify_one();
23 }
24
25 pub async fn take<F>(&self, create: F) -> T
26 where
27 F: FnOnce() -> T,
28 {
29 let mut lock_guard = (&self.sync_tuple).lock().await;
30
31 while (*lock_guard).0.is_empty() && (*lock_guard).1 == self.max {
32 lock_guard = self.cvar.wait(lock_guard).await;
33 }
34
35 if (*lock_guard).1 < self.max {
36 (*lock_guard).0.push(create());
37 (*lock_guard).1 += 1;
38 }
39
40 return (*lock_guard).0.remove(0);
41 }
42}