1 个不稳定版本
使用旧的 Rust 2015
0.1.0 | 2018年5月31日 |
---|
#29 in #对象池
7KB
139 行
BlockingObjectPool
一个 Rust 中的线程安全、阻塞、对象池。
摘要
BlockingObjectPool::with_capacity
或BlockingObjectPool::with_objects
用于初始化池pool.get
从池中获取对象
如果池为空,get
将被阻塞。
如果对象超出作用域,它将自动返回池中。
这就是全部!
示例
extern crate blocking_object_pool;
use blocking_object_pool::BlockingObjectPool;
#[derive(Clone)]
struct Hello {
a: i32,
b: i32,
}
fn main() {
let pool = BlockingObjectPool::with_capacity(2, || Hello { a: 1, b: 2 });
// get one object
let m = pool.get();
assert_eq!(m.a, 1);
println!("one. m.a={}", m.a);
// get another object.
{
let mut m = pool.get();
println!("two. m.a={}", m.a);
m.a = 11;
} // here the 2nd object goes out of scope, and it's been put back to the pool automatically.
// you can either call drop(m) manually.
let m = pool.get();
assert_eq!(m.a, 11);
println!("two again, m.a={}", m.a);
println!("this line will be blocked for ever");
let _m = pool.get();
}
灵感来自 zslayton 的 lifeguard。