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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
use crossbeam_channel::{Sender, bounded};
use std::thread;
mod unwind;
mod job;
use crate::job::{JobRef, StackJob};
type TTreeMessage = JobRef;
#[derive(Debug)]
pub struct ThreadTree {
sender: Option<Sender<TTreeMessage>>,
child: Option<[Box<ThreadTree>; 2]>,
}
impl ThreadTree {
const BOTTOM: &'static Self = &ThreadTree::new_level0();
#[inline]
pub const fn new_level0() -> Self {
ThreadTree { sender: None, child: None }
}
pub fn new_with_level(level: usize) -> Box<Self> {
assert!(level <= 12,
"Input exceeds maximum level 12 (equivalent to 2**12 - 1 threads), got level='{}'",
level);
if level == 0 {
Box::new(Self::new_level0())
} else if level == 1 {
Box::new(ThreadTree { sender: Some(Self::add_thread()), child: None })
} else {
let fork_2 = Self::new_with_level(level - 1);
let fork_3 = Self::new_with_level(level - 1);
Box::new(ThreadTree { sender: Some(Self::add_thread()), child: Some([fork_2, fork_3])})
}
}
#[inline]
pub fn is_parallel(&self) -> bool {
self.sender.is_some()
}
#[inline]
pub fn top(&self) -> ThreadTreeCtx<'_> {
ThreadTreeCtx::from(self)
}
fn add_thread() -> Sender<TTreeMessage> {
let (sender, receiver) = bounded::<TTreeMessage>(1);
std::thread::spawn(move || {
for job in receiver {
unsafe {
job.execute()
}
}
});
sender
}
}
#[derive(Debug, Copy, Clone)]
pub struct ThreadTreeCtx<'a> {
tree: &'a ThreadTree,
_not_send_sync: *const (),
}
impl ThreadTreeCtx<'_> {
#[inline]
pub(crate) fn get(&self) -> &ThreadTree { self.tree }
#[inline]
pub(crate) fn from(tree: &ThreadTree) -> ThreadTreeCtx<'_> {
ThreadTreeCtx { tree, _not_send_sync: &() }
}
#[inline]
pub fn is_parallel(&self) -> bool {
self.get().is_parallel()
}
pub fn join<A, B, RA, RB>(&self, a: A, b: B) -> (RA, RB)
where A: FnOnce(ThreadTreeCtx) -> RA + Send,
B: FnOnce(ThreadTreeCtx) -> RB + Send,
RA: Send,
RB: Send,
{
let bottom_level = ThreadTree::BOTTOM;
let self_ = self.get();
let (fork_a, fork_b) = match &self_.child {
None => (bottom_level, bottom_level),
Some([fa, fb]) => (&**fa, &**fb),
};
unsafe {
let a = move || a(ThreadTreeCtx::from(fork_a));
let b = move || b(ThreadTreeCtx::from(fork_b));
let b_job = StackJob::new(b);
let b_job_ref = JobRef::new(&b_job);
let b_runs_here = match self_.sender {
Some(ref s) => { s.send(b_job_ref).unwrap(); None }
None => Some(b_job_ref),
};
let a_result;
{
let _wait_for_b_guard = match b_runs_here {
None => Some(WaitForJobGuard::new(&b_job)),
Some(_) => None,
};
a_result = a();
if let Some(b_job_ref) = b_runs_here {
b_job_ref.execute();
}
}
(a_result, b_job.into_result())
}
}
pub fn join3l<A, RA>(&self, a: &A) -> ((RA, RA), RA)
where A: Fn(ThreadTreeCtx, usize) -> RA + Sync,
RA: Send,
{
self.join(
move |ctx| ctx.join(move |ctx| a(ctx, 0), move |ctx| a(ctx, 1)),
move |ctx| a(ctx, 2))
}
pub fn join3r<A, RA>(&self, a: &A) -> (RA, (RA, RA))
where A: Fn(ThreadTreeCtx, usize) -> RA + Sync,
RA: Send,
{
self.join(
move |ctx| a(ctx, 0),
move |ctx| ctx.join(move |ctx| a(ctx, 1), move |ctx| a(ctx, 2)))
}
pub fn join4<A, RA>(&self, a: &A) -> ((RA, RA), (RA, RA))
where A: Fn(ThreadTreeCtx, usize) -> RA + Sync,
RA: Send,
{
self.join(
move |ctx| ctx.join(move |ctx| a(ctx, 0), move |ctx| a(ctx, 1)),
move |ctx| ctx.join(move |ctx| a(ctx, 2), move |ctx| a(ctx, 3)))
}
}
fn wait_for_job<F, R>(job: &StackJob<F, R>) {
while !job.probe() {
thread::yield_now();
}
}
struct WaitForJobGuard<'a, F, R> {
job: &'a StackJob<F, R>,
}
impl<'a, F, R> WaitForJobGuard<'a, F, R>
{
fn new(job: &'a StackJob<F, R>) -> Self {
Self { job }
}
}
impl<'a, F, R> Drop for WaitForJobGuard<'a, F, R> {
fn drop(&mut self) {
wait_for_job(self.job)
}
}
#[cfg(test)]
mod thread_tree_tests {
use super::*;
#[allow(deprecated)]
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::sync::Mutex;
use once_cell::sync::Lazy;
use std::collections::HashSet;
use std::thread;
use std::thread::ThreadId;
#[allow(deprecated)]
fn sleep_ms(x: u32) {
std::thread::sleep_ms(x)
}
#[test]
fn stub() {
let tp = ThreadTree::new_level0();
let a = AtomicUsize::new(0);
let b = AtomicUsize::new(0);
tp.top().join(|_| a.fetch_add(1, Ordering::SeqCst),
|_| b.fetch_add(1, Ordering::SeqCst));
assert_eq!(a.load(Ordering::SeqCst), 1);
assert_eq!(b.load(Ordering::SeqCst), 1);
let f = || thread::current().id();
let (aid, bid) = tp.top().join(|_| f(), |_| f());
assert_eq!(aid, bid);
assert!(!tp.top().is_parallel());
}
#[test]
fn new_level_1() {
let tp = ThreadTree::new_with_level(1);
let a = AtomicUsize::new(0);
let b = AtomicUsize::new(0);
tp.top().join(|_| a.fetch_add(1, Ordering::SeqCst),
|_| b.fetch_add(1, Ordering::SeqCst));
assert_eq!(a.load(Ordering::SeqCst), 1);
assert_eq!(b.load(Ordering::SeqCst), 1);
let f = || thread::current().id();
let (aid, bid) = tp.top().join(|_| f(), |_| f());
assert_ne!(aid, bid);
assert!(tp.top().is_parallel());
}
#[test]
fn build_level_2() {
let tp = ThreadTree::new_with_level(2);
let a = AtomicUsize::new(0);
let b = AtomicUsize::new(0);
tp.top().join(|_| a.fetch_add(1, Ordering::SeqCst),
|_| b.fetch_add(1, Ordering::SeqCst));
assert_eq!(a.load(Ordering::SeqCst), 1);
assert_eq!(b.load(Ordering::SeqCst), 1);
let f = || thread::current().id();
let ((aid, bid), (cid, did)) = tp.top().join(
|tp1| tp1.join(|_| f(), |_| f()),
|tp1| tp1.join(|_| f(), |_| f()));
assert_ne!(aid, bid);
assert_ne!(aid, cid);
assert_ne!(aid, did);
assert_ne!(bid, cid);
assert_ne!(bid, did);
assert_ne!(cid, did);
}
#[test]
fn overload_2_2() {
let global = ThreadTree::new_with_level(1);
let tp = ThreadTree::new_with_level(2);
let a = AtomicUsize::new(0);
let range = 0..100;
let work = |ctx: ThreadTreeCtx<'_>| {
let subwork = || {
for i in range.clone() {
a.fetch_add(i, Ordering::Relaxed);
sleep_ms(1);
}
};
ctx.join(|_| subwork(), |_| subwork());
};
global.top().join(
|_| tp.top().join(work, work),
|_| tp.top().join(work, work));
let sum = range.clone().sum::<usize>();
assert_eq!(sum * 4 * 2, a.load(Ordering::SeqCst));
}
#[test]
fn deep_tree() {
static THREADS: Lazy<Mutex<HashSet<ThreadId>>> = Lazy::new(|| Mutex::default());
const TREE_LEVEL: usize = 8;
const MAX_DEPTH: usize = 12;
static COUNT: AtomicUsize = AtomicUsize::new(0);
let tp = ThreadTree::new_with_level(TREE_LEVEL);
fn f(tp: ThreadTreeCtx<'_>, depth: usize) {
COUNT.fetch_add(1, Ordering::SeqCst);
THREADS.lock().unwrap().insert(thread::current().id());
if depth >= MAX_DEPTH {
return;
}
tp.join(
|ctx| {
f(ctx, depth + 1);
},
|ctx| {
f(ctx, depth + 1);
});
}
COUNT.fetch_add(2, Ordering::SeqCst);
tp.top().join(|ctx| f(ctx, 2), |ctx| f(ctx, 2));
let visited_threads = THREADS.lock().unwrap().len();
assert_eq!(visited_threads, 1 << TREE_LEVEL);
assert_eq!(COUNT.load(Ordering::SeqCst), 1 << MAX_DEPTH);
}
#[test]
#[should_panic]
fn panic_a() {
let pool = ThreadTree::new_with_level(1);
pool.top().join(|_| panic!("Panic in A"), |_| 1 + 1);
}
#[test]
#[should_panic]
fn panic_b() {
let pool = ThreadTree::new_with_level(1);
pool.top().join(|_| 1 + 1, |_| panic!());
}
#[test]
#[should_panic]
fn panic_both_in_threads() {
let pool = ThreadTree::new_with_level(1);
pool.top().join(|_| { sleep_ms(50); panic!("Panic in A") }, |_| panic!("Panic in B"));
}
#[test]
#[should_panic]
fn panic_both_bottom() {
let pool = ThreadTree::new_with_level(0);
pool.top().join(|_| { sleep_ms(50); panic!("Panic in A") }, |_| panic!("Panic in B"));
}
#[test]
fn on_panic_a_wait_for_b() {
let pool = ThreadTree::new_with_level(1);
for i in 0..3 {
let start = AtomicUsize::new(0);
let finish = AtomicUsize::new(0);
let result = unwind::halt_unwinding(|| {
pool.top().join(
|_| panic!("Panic in A"),
|_| {
start.fetch_add(1, Ordering::SeqCst);
sleep_ms(50);
finish.fetch_add(1, Ordering::SeqCst);
});
});
let start_count = start.load(Ordering::SeqCst);
let finish_count = finish.load(Ordering::SeqCst);
assert_eq!(start_count, finish_count);
assert!(result.is_err());
println!("Pass {} with start: {} == finish {}", i,
start_count, finish_count);
}
}
}