-
Notifications
You must be signed in to change notification settings - Fork 41
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
74 additions
and
11 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
//! Resource pool implementation | ||
// TODO: automatic return resource to the pool with Guard and Drop | ||
// TODO: avoid returning stale resources | ||
// TODO: add tests | ||
use std::{ | ||
collections::VecDeque, | ||
sync::{Condvar, Mutex}, | ||
}; | ||
|
||
/// Resource pool | ||
pub struct ResourcePool<T: Send + Sync> { | ||
resources: Mutex<VecDeque<T>>, | ||
not_empty: Condvar, | ||
} | ||
|
||
impl<T: Send + Sync> ResourcePool<T> { | ||
/// Create a new resource pool | ||
pub fn new(resources: Vec<T>) -> Self { | ||
Self { | ||
resources: Mutex::new(resources.into()), | ||
not_empty: Condvar::new(), | ||
} | ||
} | ||
|
||
/// Acquire a resource from the pool | ||
pub async fn acquire_resource(&self) -> T { | ||
let mut resources = self.resources.lock().unwrap(); | ||
while resources.is_empty() { | ||
resources = self.not_empty.wait(resources).unwrap(); | ||
} | ||
resources.pop_front().unwrap() | ||
} | ||
|
||
/// Return a resource to the pool | ||
// TODO: automatic return resource to the pool with Guard and Drop | ||
pub async fn return_resource(&self, resource: T) { | ||
let mut resources = self.resources.lock().unwrap(); | ||
resources.push_back(resource); | ||
self.not_empty.notify_one(); | ||
} | ||
|
||
/// Drain the pool | ||
pub async fn drain(&self) { | ||
let mut resources = self.resources.lock().unwrap(); | ||
let _ = resources.drain(..).collect::<Vec<_>>(); | ||
} | ||
|
||
/// Count the resources in the pool | ||
pub async fn count(&self) -> usize { | ||
self.resources.lock().unwrap().len() | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests {} |