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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
use {
crate::{
accounts_index::{AccountsIndexConfig, IndexValue},
bucket_map_holder::BucketMapHolder,
in_mem_accounts_index::InMemAccountsIndex,
waitable_condvar::WaitableCondvar,
},
std::{
fmt::Debug,
sync::{
atomic::{AtomicBool, Ordering},
Arc, Mutex,
},
thread::{Builder, JoinHandle},
},
};
pub struct AccountsIndexStorage<T: IndexValue> {
_bg_threads: BgThreads,
pub storage: Arc<BucketMapHolder<T>>,
pub in_mem: Vec<Arc<InMemAccountsIndex<T>>>,
startup_worker_threads: Mutex<Option<BgThreads>>,
}
impl<T: IndexValue> Debug for AccountsIndexStorage<T> {
fn fmt(&self, _f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Ok(())
}
}
struct BgThreads {
exit: Arc<AtomicBool>,
handles: Option<Vec<JoinHandle<()>>>,
wait: Arc<WaitableCondvar>,
}
impl Drop for BgThreads {
fn drop(&mut self) {
self.exit.store(true, Ordering::Relaxed);
self.wait.notify_all();
if let Some(handles) = self.handles.take() {
handles
.into_iter()
.for_each(|handle| handle.join().unwrap());
}
}
}
impl BgThreads {
fn new<T: IndexValue>(
storage: &Arc<BucketMapHolder<T>>,
in_mem: &[Arc<InMemAccountsIndex<T>>],
threads: usize,
) -> Self {
let exit = Arc::new(AtomicBool::default());
let handles = Some(
(0..threads)
.into_iter()
.map(|_| {
let storage_ = Arc::clone(storage);
let exit_ = Arc::clone(&exit);
let in_mem_ = in_mem.to_vec();
Builder::new()
.name("solana-idx-flusher".to_string())
.spawn(move || {
storage_.background(exit_, in_mem_);
})
.unwrap()
})
.collect(),
);
BgThreads {
exit,
handles,
wait: Arc::clone(&storage.wait_dirty_or_aged),
}
}
}
impl<T: IndexValue> AccountsIndexStorage<T> {
pub fn set_startup(&self, value: bool) {
if value {
*self.startup_worker_threads.lock().unwrap() = Some(BgThreads::new(
&self.storage,
&self.in_mem,
Self::num_threads(),
));
}
self.storage.set_startup(value);
if !value {
*self.startup_worker_threads.lock().unwrap() = None;
}
}
fn num_threads() -> usize {
std::cmp::max(2, num_cpus::get() / 4)
}
pub fn new(bins: usize, config: &Option<AccountsIndexConfig>) -> Self {
let threads = config
.as_ref()
.and_then(|config| config.flush_threads)
.unwrap_or_else(Self::num_threads);
let storage = Arc::new(BucketMapHolder::new(bins, config, threads));
let in_mem = (0..bins)
.into_iter()
.map(|bin| Arc::new(InMemAccountsIndex::new(&storage, bin)))
.collect::<Vec<_>>();
Self {
_bg_threads: BgThreads::new(&storage, &in_mem, threads),
storage,
in_mem,
startup_worker_threads: Mutex::default(),
}
}
}