3个不稳定版本
0.2.2 | 2020年3月2日 |
---|---|
0.2.1 |
|
0.2.0 |
|
0.1.1 | 2020年2月27日 |
0.1.0 | 2020年2月27日 |
#998 在 并发 中
115,139 每月下载量
在 2 crates 中使用
14KB
315 行
dynamic-pool
一个无锁、线程安全、动态大小的对象池。
此池从初始容量开始,在请求时没有可用对象时将继续创建新对象。池化的对象在销毁时会返回到池中(并提供额外的选择以可选“重置”对象状态以供重用)。
如果在尝试返回时池中已有 maximum_capacity
个对象,则池会丢弃该对象。
基本用法
将此添加到您的 Cargo.toml
[dependencies]
dynamic-pool = "0.1"
然后,进行一些池化操作
use dynamic_pool::{DynamicPool, DynamicReset};
#[derive(Default)]
struct Person {
name: String,
age: u16,
}
impl DynamicReset for Person {
fn reset(&mut self) {
self.name.clear();
self.age = 0;
}
}
fn main() {
// Creates a new pool that will hold at most 10 items, starting with 1 item by default.
let pool = DynamicPool::new(1, 10, Person::default);
// Assert we have one item in the pool.
assert_eq!(pool.available(), 1);
// Take an item from the pool.
let mut person = pool.take();
person.name = "jake".into();
person.age = 99;
// Assert the pool is empty since we took the person above.
assert_eq!(pool.available(), 0);
// Dropping returns the item to the pool.
drop(person);
// We now have stuff available in the pool to take.
assert_eq!(pool.available(), 1);
// Take person from the pool again, it should be reset.
let person = pool.take();
assert_eq!(person.name, "");
assert_eq!(person.age, 0);
// Nothing is in the queue.
assert_eq!(pool.available(), 0);
// try_take returns an Option. Since the pool is empty, nothing will be created.
assert!(pool.try_take().is_none());
// Dropping again returns the person to the pool.
drop(person);
// We have stuff in the pool now!
assert_eq!(pool.available(), 1);
// try_take would succeed here!
let person = pool.try_take().unwrap();
// We can also then detach the `person` from the pool, meaning it won't get
// recycled.
let person = person.detach();
// We can then drop that person, and see that it's not returned to the pool.
drop(person);
assert_eq!(pool.available(), 0);
}
许可证
根据 MIT 许可证 许可。
依赖项
~215KB