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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
use crate::api::BitcoinDB;
use crate::iter::util::get_task;
use bitcoin::Block;
use std::collections::VecDeque;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{channel, sync_channel, Receiver, SyncSender};
use std::sync::{Arc, Mutex};
use std::thread;
use std::thread::JoinHandle;
const MAX_SIZE_FOR_THREAD: usize = 10;
pub struct BlockIter<TBlock> {
receivers: Vec<Receiver<TBlock>>,
task_order: Receiver<(usize, usize)>,
heights: Vec<usize>,
current: usize,
worker_thread: Option<Vec<JoinHandle<()>>>,
iterator_stopper: Arc<AtomicBool>,
is_killed: bool,
}
impl<TBlock> BlockIter<TBlock>
where
TBlock: From<Block> + Send + 'static,
{
pub fn new(db: &BitcoinDB, heights: Vec<usize>) -> Self {
let cpus = num_cpus::get();
let iterator_stopper = Arc::new(AtomicBool::new(false));
let (task_register, task_order) = channel();
let tasks: VecDeque<usize> = heights.clone().into_iter().collect();
let tasks = Arc::new(Mutex::new(tasks));
let mut handles = Vec::with_capacity(cpus);
let mut receivers = Vec::with_capacity(cpus);
for thread_number in 0..cpus {
let (sender, receiver) = sync_channel(MAX_SIZE_FOR_THREAD);
let task = tasks.clone();
let register = task_register.clone();
let iterator_stopper = iterator_stopper.clone();
let db = db.clone();
let handle = thread::spawn(move || {
loop {
if iterator_stopper.load(Ordering::SeqCst) {
break;
}
match get_task(&task, ®ister, thread_number) {
None => break,
Some(task) => {
if !fetch_block(&db, task, &sender) {
iterator_stopper.fetch_or(true, Ordering::SeqCst);
break;
}
}
}
}
});
receivers.push(receiver);
handles.push(handle);
}
BlockIter {
receivers,
task_order,
heights,
current: 0,
worker_thread: Some(handles),
iterator_stopper,
is_killed: false,
}
}
pub fn from_range(db: &BitcoinDB, start: usize, end: usize) -> Self {
if end <= start {
BlockIter::new(db, Vec::new())
} else {
let heights: Vec<usize> = (start..end).collect();
BlockIter::new(db, heights)
}
}
}
impl<T> BlockIter<T> {
fn kill(&mut self) {
if !self.is_killed {
self.iterator_stopper.fetch_or(true, Ordering::SeqCst);
loop {
let _ = match self.task_order.recv() {
Ok((_, thread_number)) => self.receivers.get(thread_number).unwrap().recv(),
Err(_) => break,
};
}
self.is_killed = true;
}
}
}
impl<TBlock> Iterator for BlockIter<TBlock> {
type Item = TBlock;
fn next(&mut self) -> Option<Self::Item> {
if self.is_killed {
return None;
}
match self.task_order.recv() {
Ok((height, thread_number)) => {
let current_height = *self
.heights
.get(self.current)
.expect("report this, shouldn't reach here, must debug");
if height != current_height {
self.kill();
return None;
}
match self.receivers.get(thread_number).unwrap().recv() {
Ok(block) => {
self.current += 1;
Some(block)
}
Err(_) => {
self.kill();
None
}
}
}
Err(_) => None,
}
}
}
impl<T> BlockIter<T> {
fn join(&mut self) {
for handle in self.worker_thread.take().unwrap() {
handle.join().unwrap()
}
}
}
impl<T> Drop for BlockIter<T> {
fn drop(&mut self) {
self.kill();
self.join();
}
}
#[inline]
pub(crate) fn fetch_block<T>(db: &BitcoinDB, height: usize, sender: &SyncSender<T>) -> bool
where
T: From<Block>,
{
match db.get_block::<T>(height) {
Ok(blk) => {
sender.send(blk).unwrap();
true
}
Err(_) => {
return false;
}
}
}