/
thread_pool.rs
83 lines (75 loc) · 2.49 KB
/
thread_pool.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
use once_cell::sync::Lazy;
use parking_lot::RwLock;
use scheduled_thread_pool::ScheduledThreadPool;
use std::{collections::HashMap, sync::Arc};
static REGISTRY: Lazy<ThreadPoolRegistry> = Lazy::new(ThreadPoolRegistry::default);
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
pub(crate) enum PoolName {
Housekeeper,
Invalidator,
}
impl PoolName {
fn thread_name_template(&self) -> &'static str {
match self {
PoolName::Housekeeper => "moka-housekeeper-{}",
PoolName::Invalidator => "moka-invalidator-{}",
}
}
}
pub(crate) struct ThreadPool {
pub(crate) name: PoolName,
pub(crate) pool: ScheduledThreadPool,
// pub(crate) num_threads: usize,
}
pub(crate) struct ThreadPoolRegistry {
pools: RwLock<HashMap<PoolName, Arc<ThreadPool>>>,
}
impl Default for ThreadPoolRegistry {
fn default() -> Self {
Self {
pools: RwLock::new(HashMap::default()),
}
}
}
impl ThreadPoolRegistry {
pub(crate) fn acquire_pool(name: PoolName) -> Arc<ThreadPool> {
loop {
{
// Acquire a read lock and get the pool.
let pools = REGISTRY.pools.read();
if let Some(pool) = pools.get(&name) {
return Arc::clone(pool);
}
}
{
// Acquire the write lock, double check the pool still does not exist,
// and insert a new pool.
let mut pools = REGISTRY.pools.write();
pools.entry(name).or_insert_with(|| {
let num_threads = num_cpus::get();
let pool =
ScheduledThreadPool::with_name(name.thread_name_template(), num_threads);
let t_pool = ThreadPool {
name,
pool,
// num_threads,
};
Arc::new(t_pool)
});
}
}
}
pub(crate) fn release_pool(pool: &Arc<ThreadPool>) {
if Arc::strong_count(pool) <= 2 {
// No other client exists; only this Arc and the registry are
// the owners. Let's remove and drop the one in the registry.
let name = pool.name;
let mut pools = REGISTRY.pools.write();
if let Some(pool) = pools.get(&name) {
if Arc::strong_count(pool) <= 2 {
pools.remove(&name);
}
}
}
}
}