#对象池 #无锁 #线程安全 #容量 #动态大小 #重置 #初始

dynamic-pool

一个无锁、线程安全、动态大小的对象池

3个不稳定版本

0.2.2 2020年3月2日
0.2.1 2020年3月2日
0.2.0 2020年3月2日
0.1.1 2020年2月27日
0.1.0 2020年2月27日

#998并发

Download history 31934/week @ 2024-03-14 22252/week @ 2024-03-21 44312/week @ 2024-03-28 19472/week @ 2024-04-04 22869/week @ 2024-04-11 25240/week @ 2024-04-18 22304/week @ 2024-04-25 20581/week @ 2024-05-02 23045/week @ 2024-05-09 33948/week @ 2024-05-16 28347/week @ 2024-05-23 20897/week @ 2024-05-30 32593/week @ 2024-06-06 25681/week @ 2024-06-13 27071/week @ 2024-06-20 23702/week @ 2024-06-27

115,139 每月下载量
2 crates 中使用

MIT 许可证

14KB
315

dynamic-pool

Build Status License Documentation Cargo

一个无锁、线程安全、动态大小的对象池。

此池从初始容量开始,在请求时没有可用对象时将继续创建新对象。池化的对象在销毁时会返回到池中(并提供额外的选择以可选“重置”对象状态以供重用)。

如果在尝试返回时池中已有 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