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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
use std::{
cmp,
sync::{
atomic::{AtomicBool, AtomicUsize, Ordering},
mpsc, Arc, Mutex,
},
thread::{self, JoinHandle},
};
extern crate crossbeam_deque;
extern crate crossbeam_utils;
use super::{
error::TaskError,
topology::{TaskNode, Topology},
};
pub trait Worker {
fn ready(&self, topology: &Topology) -> Result<(), TaskError>;
fn execute(&self) -> Result<(), TaskError>;
fn wait_finish(&self);
}
pub struct SequentialWorker {
tx: mpsc::Sender<TaskNode>,
rx: mpsc::Receiver<TaskNode>,
task_count: AtomicUsize,
}
impl SequentialWorker {
pub fn new() -> Self {
let (tx, rx) = mpsc::channel::<TaskNode>();
Self {
tx,
rx,
task_count: AtomicUsize::new(0),
}
}
}
impl Worker for SequentialWorker {
fn ready(&self, topology: &Topology) -> Result<(), TaskError> {
for root_group in &topology.root_groups {
let root_group = root_group.upgrade().unwrap();
for task in &root_group.lock().unwrap().task_nodes {
self.tx.send(task.clone()).unwrap();
}
}
self.task_count
.store(topology.task_count, Ordering::Relaxed);
Ok(())
}
fn execute(&self) -> Result<(), TaskError> {
loop {
let task = self.rx.try_recv();
if task.is_err() {
assert!(
self.task_count.load(Ordering::Relaxed) == 0,
"Topology's total task count must be matched."
);
break;
}
let task = task.unwrap();
if let Some(accessor) = task.handle.value_as_ref() {
accessor.call();
};
self.task_count.fetch_sub(1, Ordering::Relaxed);
let group = task.group_node.upgrade().unwrap();
let group_lock = group.lock().unwrap();
let last_count = group_lock.decrease_task_count();
if last_count == 1 {
for successor in &group_lock.successor_nodes {
let successor = successor.upgrade().unwrap();
let successor = successor.lock().unwrap();
let last_count = successor.decrease_predecessor_count();
if last_count == 1 {
for task in &successor.task_nodes {
self.tx.send(task.clone()).unwrap();
}
}
}
}
}
Ok(())
}
fn wait_finish(&self) {
let backoff = crossbeam_utils::Backoff::new();
while self.task_count.load(Ordering::Relaxed) != 0 {
backoff.spin();
}
}
}
struct BlockedThreads {
list: Vec<thread::Thread>,
insertable: bool,
}
impl BlockedThreads {
pub fn new() -> Self {
Self {
list: vec![],
insertable: true,
}
}
pub fn is_insertable(&self) -> bool {
self.insertable
}
pub fn push(&mut self, thread: thread::Thread) {
assert!(
self.insertable == true,
"This function must only be called when is_insertable() is true."
);
self.list.push(thread);
}
pub fn try_unparks_of(&mut self, count: usize) {
self.list
.drain(0..count)
.into_iter()
.for_each(|t| t.unpark());
}
pub fn unpark_all(&mut self) {
self.list.drain(..).into_iter().for_each(|t| t.unpark());
}
}
pub struct ThreadingWorker {
global_fifo: Arc<crossbeam_deque::Injector<TaskNode>>,
threads: Vec<JoinHandle<()>>,
blocked_threads: Arc<Mutex<BlockedThreads>>,
is_worker_terminated: Arc<AtomicBool>,
task_count: Arc<AtomicUsize>,
}
impl ThreadingWorker {
pub fn try_new_automatic() -> Option<Self> {
let available_concurrency = thread::available_concurrency()
.map(|n| n.get())
.unwrap_or(1);
Self::try_new(available_concurrency)
}
pub fn try_new(hardware_concurrency: usize) -> Option<Self> {
if hardware_concurrency == 0 {
return None;
}
let is_worker_terminated = Arc::new(AtomicBool::new(false));
let global_fifo = Arc::new(crossbeam_deque::Injector::<TaskNode>::new());
let blocked_threads = Arc::new(Mutex::new(BlockedThreads::new()));
let task_count = Arc::new(AtomicUsize::new(0));
let threads: Vec<_> = (0..hardware_concurrency)
.into_iter()
.map(|id| {
let is_worker_terminated = is_worker_terminated.clone();
let global_fifo = global_fifo.clone();
let blocked_threads = blocked_threads.clone();
let task_count = task_count.clone();
let backoff = crossbeam_utils::Backoff::new();
thread::Builder::new()
.name(format!("ThreadingWorker thread_index:{}", id).into())
.spawn(move || loop {
if is_worker_terminated.load(Ordering::Acquire) {
return ();
}
let task = loop {
let t = global_fifo.steal();
if t.is_success() {
backoff.reset();
break t.success().unwrap();
}
if t.is_empty() {
let is_inserted = {
let mut guard = blocked_threads.lock().unwrap();
if guard.is_insertable() {
guard.push(thread::current());
true
} else {
false
}
};
if is_inserted {
thread::park();
}
if is_worker_terminated.load(Ordering::SeqCst) {
return ();
}
}
backoff.spin();
};
if let Some(accessor) = task.handle.value_as_ref() {
accessor.call();
};
task_count.fetch_sub(1, Ordering::AcqRel);
let group = task.group_node.upgrade().unwrap();
let group = group.lock().unwrap();
let cnt = group.decrease_task_count();
if cnt == 1 {
for successor in &group.successor_nodes {
let successor = successor.upgrade().unwrap();
let successor = successor.lock().unwrap();
let last_count = successor.decrease_predecessor_count();
if last_count == 1 {
let wake_count = cmp::min(
successor.task_count() as usize,
hardware_concurrency,
);
for task in &successor.task_nodes {
global_fifo.push(task.clone());
}
let mut guard = blocked_threads.lock().unwrap();
guard.try_unparks_of(wake_count);
}
}
}
})
.unwrap()
})
.collect();
Some(Self {
global_fifo,
threads,
blocked_threads,
is_worker_terminated,
task_count,
})
}
}
impl Worker for ThreadingWorker {
fn ready(&self, topology: &Topology) -> Result<(), TaskError> {
self.task_count.store(topology.task_count, Ordering::SeqCst);
for root_group in &topology.root_groups {
let root_group = root_group.upgrade().unwrap();
for task in &root_group.lock().unwrap().task_nodes {
self.global_fifo.push(task.clone());
}
}
Ok(())
}
fn execute(&self) -> Result<(), TaskError> {
let mut threads = self.blocked_threads.lock().unwrap();
threads.unpark_all();
Ok(())
}
fn wait_finish(&self) {
let backoff = crossbeam_utils::Backoff::new();
while self.task_count.load(Ordering::Relaxed) != 0 {
backoff.spin();
}
}
}
impl Drop for ThreadingWorker {
fn drop(&mut self) {
self.is_worker_terminated.store(true, Ordering::SeqCst);
self.wait_finish();
{
let mut threads = self.blocked_threads.lock().unwrap();
threads.insertable = false;
threads.unpark_all();
}
self.threads.drain(..).for_each(|h| h.join().unwrap());
}
}
#[cfg(test)]
mod tests {
#[test]
fn thread_test1() {
use std::thread;
let available_concurrency = thread::available_concurrency()
.map(|n| n.get())
.unwrap_or(1);
let threads = (0..available_concurrency)
.into_iter()
.map(|cnt| {
thread::spawn(move || {
println!("This is thread {}.", cnt);
})
})
.collect::<Vec<_>>();
for thread in threads.into_iter() {
thread.join().unwrap();
}
}
}