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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
use std::fmt;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::thread::{spawn, JoinHandle};
use std::time::Duration;
use crossbeam_channel::{bounded, select, select_biased, tick};
use genzero;
use quanta::Clock;
use super::channel::*;
use super::err::ThreadPoolError;
const UPDATE_SIZE: u8 = 0;
const STOP_THREAD: u8 = 1;
/// Struct containing thread pool metrics, that is updated every approx. every 10 seconds.
#[derive(Default, Clone, Copy)]
pub struct Metrics {
/// Current number of running threads, which may temporarily differ from [`ThreadPool::get_pool_size`].
pub active_threads: usize,
pub input_channel_len: usize,
pub input_channel_capacity: Option<usize>,
pub output_channel_len: usize,
pub output_channel_capacity: Option<usize>,
/// Total executions of the provided function since the last metrics update.
/// Inputs that have been executed on, but not sent are not counted until they have sent;
pub execution_count: usize,
/// Average nano-second execution duration of the provided function since the last metrics update.
/// Does not include any time the input/output spends in the channels.
pub average_execution_duration_ns: usize,
// pub minimum_execution_duration_ns: usize,
// pub maximum_execution_duration_ns: usize,
}
struct ExecutionMetrics {
clock: Clock,
execution_counter: AtomicUsize,
total_execution_time_ns: AtomicUsize,
// min_execution_time_ns: AtomicUsize,
// max_execution_time_ns: AtomicUsize,
}
impl ExecutionMetrics {
fn new() -> Self {
ExecutionMetrics {
clock: Clock::new(),
execution_counter: AtomicUsize::new(0),
total_execution_time_ns: AtomicUsize::new(0),
}
}
fn update(&self, execution_time: usize) {
self.execution_counter.fetch_add(1, Ordering::Relaxed);
self.total_execution_time_ns
.fetch_add(execution_time, Ordering::Relaxed);
}
fn get_and_reset_execution_count(&self) -> usize {
self.execution_counter.fetch_and(0, Ordering::Relaxed)
}
fn get_and_reset_total_execution_time_ns(&self) -> usize {
self.total_execution_time_ns.fetch_and(0, Ordering::Relaxed)
}
}
/// The thread pool of a lambda-channel that spawns threads running an infinite loop.
/// The thread loop waits for a message from the input channel, executes a provided function,
/// and sends the result to the output channel if the function has an output.
///
/// The pool starts with one control thread, all additional threads are normal worker threads.
/// The control thread is identical to a normal worker thread, but also handles metrics collection, pool resizing, and termination propagation.
///
/// If the pool is dropped, the threads will automatically terminate.
/// If the input channel or output channel to the thread pool disconnects, the threads will automatically terminate.
/// If the thread is executing on an input or waiting to send an output when termination is triggered, it will finish execution and send the
/// output value before terminating.
#[derive(Clone)]
pub struct ThreadPool {
desired_threads: Arc<AtomicUsize>,
control_tx: crossbeam_channel::Sender<u8>,
metrics_rx: genzero::Receiver<Metrics>,
}
impl ThreadPool {
pub(super) fn new_lambda_pool<
T: Send + 'static,
U: Send + 'static,
V: Clone + Send + 'static,
>(
input_channel: Receiver<T>,
output_channel: Sender<U>,
shared_resource: V,
function: fn(&V, T) -> U,
) -> Self {
let desired_threads = Arc::new(AtomicUsize::new(1));
let (control_tx, metrics_rx) = spawn_primary_lambda_thread(
input_channel,
output_channel,
shared_resource,
function,
desired_threads.clone(),
);
Self {
desired_threads,
control_tx,
metrics_rx,
}
}
pub(super) fn new_sink_pool<T: Send + 'static, V: Clone + Send + 'static>(
input_channel: Receiver<T>,
shared_resource: V,
function: fn(&V, T),
) -> Self {
let desired_threads = Arc::new(AtomicUsize::new(1));
let (control_tx, metrics_rx) = spawn_primary_sink_thread(
input_channel,
shared_resource,
function,
desired_threads.clone(),
);
Self {
desired_threads,
control_tx,
metrics_rx,
}
}
/// Returns the target number of threads in the pool. The actual number of threads may temporarily differ
/// when resizing the pool.
pub fn get_pool_size(&self) -> usize {
self.desired_threads.load(Ordering::Acquire)
}
/// Sets the target number of threads in the pool. The actual number of threads may temporarily differ
/// when resizing the pool.
///
/// This function will return the desired thread size if successful, or a [`ThreadPoolError`] if not.
pub fn set_pool_size(&self, n: usize) -> Result<usize, ThreadPoolError> {
if n < 1 {
return Err(ThreadPoolError::ValueError);
}
self.desired_threads.store(n, Ordering::Relaxed);
match self.control_tx.send(UPDATE_SIZE) {
Ok(_) => Ok(n),
Err(_) => Err(ThreadPoolError::ThreadsLost),
}
}
/// Returns the latest metric values, which is updated approx. every 10 seconds.
/// Calling this function between updates, will return the same values.
pub fn get_metrics(&self) -> Metrics {
self.metrics_rx.recv().unwrap()
}
}
impl fmt::Display for ThreadPool {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
"Lambda Channel Thread Pool".fmt(f)
}
}
fn spawn_primary_lambda_thread<T: Send + 'static, U: Send + 'static, V: Clone + Send + 'static>(
input_channel: Receiver<T>,
output_channel: Sender<U>,
shared_resource: V,
function: fn(&V, T) -> U,
desired_threads: Arc<AtomicUsize>,
) -> (crossbeam_channel::Sender<u8>, genzero::Receiver<Metrics>) {
let (control_tx, control_rx) = bounded(0);
let (mut metrics_tx, metrics_rx) = genzero::new(Metrics::default());
spawn(move || {
let mut threads = Vec::new();
let ticker = tick(Duration::from_secs(10));
let execution_metrics = Arc::new(ExecutionMetrics::new());
let input_channel_capacity = input_channel.capacity();
let output_channel_capacity = output_channel.capacity();
'main: loop {
select_biased! {
recv(output_channel.liveness_check) -> _ => {
break 'main;
},
recv(control_rx) -> c => {
let command = match c {
Ok(v) => v,
Err(_) => {
break 'main;
}
};
match command {
UPDATE_SIZE => {
let target = desired_threads.load(Ordering::Relaxed);
let current = threads.len() + 1;
if current < target {
for _ in 0..target-current {
threads.push(spawn_worker_lambda_thread(
input_channel.clone(),
output_channel.clone(),
shared_resource.clone(),
function,
execution_metrics.clone(),
));
}
} else {
for _ in 0..current-target {
let (control_tx, _) = threads.pop().unwrap();
let _ = control_tx.send(STOP_THREAD);
}
}
},
STOP_THREAD => {
break 'main;
},
_ => {}
}
},
recv(ticker) -> _ => {
let thread_count = threads.len();
threads.retain(|thread| {
let delete = thread.1.is_finished();
!delete
});
let failed_threads = thread_count - threads.len();
for _ in 0..failed_threads {
threads.push(spawn_worker_lambda_thread(
input_channel.clone(),
output_channel.clone(),
shared_resource.clone(),
function,
execution_metrics.clone(),
));
}
let execution_count = execution_metrics.get_and_reset_execution_count();
let average_execution_duration_ns = match execution_count {
0 => 0,
_ => execution_metrics.get_and_reset_total_execution_time_ns() / execution_count,
};
metrics_tx.send(Metrics{
active_threads: threads.len() + 1,
input_channel_len: input_channel.len(),
input_channel_capacity,
output_channel_len: output_channel.len(),
output_channel_capacity,
execution_count,
average_execution_duration_ns,
// minimum_execution_duration_ns: 0,
// maximum_execution_duration_ns: 0,
});
},
recv(input_channel.receiver) -> msg => {
let input = match msg {
Ok(v) => v,
Err(_) => {
break 'main;
}
};
let start_time = execution_metrics.clock.now();
let output = function(&shared_resource, input);
let execution_time = start_time.elapsed().as_nanos() as usize;
'inner: loop {
select! {
recv(control_rx) -> c => {
let command = match c {
Ok(v) => v,
Err(_) => {
break 'main;
}
};
match command {
UPDATE_SIZE => {
let target = desired_threads.load(Ordering::Relaxed);
let current = threads.len() + 1;
if current < target {
for _ in 0..target-current {
threads.push(spawn_worker_lambda_thread(
input_channel.clone(),
output_channel.clone(),
shared_resource.clone(),
function,
execution_metrics.clone(),
));
}
} else {
for _ in 0..current-target {
let (control_tx, _) = threads.pop().unwrap();
let _ = control_tx.send(STOP_THREAD);
}
}
},
STOP_THREAD => {
break 'main;
},
_ => {}
}
},
recv(ticker) -> _ => {
let thread_count = threads.len();
threads.retain(|thread| {
let delete = thread.1.is_finished();
!delete
});
let failed_threads = thread_count - threads.len();
for _ in 0..failed_threads {
threads.push(spawn_worker_lambda_thread(
input_channel.clone(),
output_channel.clone(),
shared_resource.clone(),
function,
execution_metrics.clone(),
));
}
let execution_count = execution_metrics.get_and_reset_execution_count();
let average_execution_duration_ns = match execution_count {
0 => 0,
_ => execution_metrics.get_and_reset_total_execution_time_ns() / execution_count,
};
metrics_tx.send(Metrics{
active_threads: threads.len() + 1,
input_channel_len: input_channel.len(),
input_channel_capacity,
output_channel_len: output_channel.len(),
output_channel_capacity,
execution_count,
average_execution_duration_ns,
// minimum_execution_duration_ns: 0,
// maximum_execution_duration_ns: 0,
});
},
send(output_channel.sender, output) -> result => {
match result {
Ok(_) => {
execution_metrics.update(execution_time);
break 'inner;
}
Err(_) => {
break 'main;
}
}
}
}
}
}
}
}
});
(control_tx, metrics_rx)
}
fn spawn_worker_lambda_thread<T: Send + 'static, U: Send + 'static, V: Clone + Send + 'static>(
input_channel: Receiver<T>,
output_channel: Sender<U>,
shared_resource: V,
function: fn(&V, T) -> U,
execution_metrics: Arc<ExecutionMetrics>,
) -> (crossbeam_channel::Sender<u8>, JoinHandle<()>) {
let (control_tx, control_rx) = bounded(0);
let handle = spawn(move || 'main: loop {
select_biased! {
recv(output_channel.liveness_check) -> _ => {
break 'main;
},
recv(control_rx) -> c => {
let command = match c {
Ok(v) => v,
Err(_) => {
break 'main;
}
};
if command == STOP_THREAD {
break 'main;
}
},
recv(input_channel.receiver) -> msg => {
let input = match msg {
Ok(v) => v,
Err(_) => {
break 'main;
}
};
let start_time = execution_metrics.clock.now();
let output = function(&shared_resource, input);
let execution_time = start_time.elapsed().as_nanos() as usize;
'inner: loop {
select! {
recv(control_rx) -> c => {
let command = match c {
Ok(v) => v,
Err(_) => {
drop(input_channel);
let _ = output_channel.send(output);
break 'main;
}
};
if command == STOP_THREAD {
drop(input_channel);
let _ = output_channel.send(output);
break 'main;
}
},
send(output_channel.sender, output) -> result => {
match result {
Ok(_) => {
execution_metrics.update(execution_time);
break 'inner;
}
Err(_) => {
break 'main;
}
}
}
}
}
}
}
});
(control_tx, handle)
}
fn spawn_primary_sink_thread<T: Send + 'static, V: Clone + Send + 'static>(
input_channel: Receiver<T>,
shared_resource: V,
function: fn(&V, T),
desired_threads: Arc<AtomicUsize>,
) -> (crossbeam_channel::Sender<u8>, genzero::Receiver<Metrics>) {
let (control_tx, control_rx) = bounded(0);
let (mut metrics_tx, metrics_rx) = genzero::new(Metrics::default());
spawn(move || {
let mut threads = Vec::new();
let ticker = tick(Duration::from_secs(10));
let execution_metrics = Arc::new(ExecutionMetrics::new());
let input_channel_capacity = input_channel.capacity();
let output_channel_capacity = None;
'main: loop {
select_biased! {
recv(control_rx) -> c => {
let command = match c {
Ok(v) => v,
Err(_) => {
break 'main;
}
};
match command {
UPDATE_SIZE => {
let target = desired_threads.load(Ordering::Relaxed);
let current = threads.len() + 1;
if current < target {
for _ in 0..target-current {
threads.push(spawn_worker_sink_thread(
input_channel.clone(),
shared_resource.clone(),
function,
execution_metrics.clone(),
));
}
} else {
for _ in 0..current-target {
let (control_tx, _) = threads.pop().unwrap();
let _ = control_tx.send(STOP_THREAD);
}
}
},
STOP_THREAD => {
break 'main;
},
_ => {}
}
},
recv(ticker) -> _ => {
let thread_count = threads.len();
threads.retain(|thread| {
let delete = thread.1.is_finished();
!delete
});
let failed_threads = thread_count - threads.len();
for _ in 0..failed_threads {
threads.push(spawn_worker_sink_thread(
input_channel.clone(),
shared_resource.clone(),
function,
execution_metrics.clone(),
));
}
let execution_count = execution_metrics.get_and_reset_execution_count();
let average_execution_duration_ns = match execution_count {
0 => 0,
_ => execution_metrics.get_and_reset_total_execution_time_ns() / execution_count,
};
metrics_tx.send(Metrics{
active_threads: threads.len() + 1,
input_channel_len: input_channel.len(),
input_channel_capacity,
output_channel_len: 0,
output_channel_capacity,
execution_count,
average_execution_duration_ns,
// minimum_execution_duration_ns: 0,
// maximum_execution_duration_ns: 0,
});
},
recv(input_channel.receiver) -> msg => {
let input = match msg {
Ok(v) => v,
Err(_) => {
break 'main;
}
};
let start_time = execution_metrics.clock.now();
function(&shared_resource, input);
let execution_time = start_time.elapsed().as_nanos() as usize;
execution_metrics.update(execution_time);
}
}
}
});
(control_tx, metrics_rx)
}
fn spawn_worker_sink_thread<T: Send + 'static, V: Clone + Send + 'static>(
input_channel: Receiver<T>,
shared_resource: V,
function: fn(&V, T),
execution_metrics: Arc<ExecutionMetrics>,
) -> (crossbeam_channel::Sender<u8>, JoinHandle<()>) {
let (control_tx, control_rx) = bounded(0);
let handle = spawn(move || 'main: loop {
select_biased! {
recv(control_rx) -> c => {
let command = match c {
Ok(v) => v,
Err(_) => {
break 'main;
}
};
if command == STOP_THREAD {
break 'main;
}
},
recv(input_channel.receiver) -> msg => {
let input = match msg {
Ok(v) => v,
Err(_) => {
break 'main;
}
};
let start_time = execution_metrics.clock.now();
function(&shared_resource, input);
let execution_time = start_time.elapsed().as_nanos() as usize;
execution_metrics.update(execution_time);
}
}
});
(control_tx, handle)
}
#[cfg(test)]
mod tests {
use crate::new_lambda_channel;
use super::*;
use std::thread::sleep;
fn simple_task(_: &Option<()>, x: u32) -> f32 {
x as f32
}
fn io_task(_: &Option<()>, x: u32) -> f32 {
sleep(Duration::from_millis(10));
(x as f32) / 3.0
}
#[test]
fn single_worker() {
let tasks = 100usize;
let capacity = 10;
let (tx, rx, _pool) = new_lambda_channel(Some(capacity), Some(capacity), None, simple_task);
spawn(move || {
for i in 0..tasks {
tx.send(i as u32).unwrap();
}
});
let mut c = 0usize;
while rx.recv().is_ok() {
c += 1;
}
assert_eq!(c, tasks);
}
#[test]
fn many_workers() {
let tasks = 100usize;
let capacity = 10;
let (tx, rx, pool) = new_lambda_channel(Some(capacity), Some(capacity), None, io_task);
assert_eq!(pool.set_pool_size(4), Ok(4));
let clock = Clock::new();
let start = clock.now();
spawn(move || {
for i in 0..tasks {
tx.send(i as u32).unwrap();
}
});
let mut c = 0usize;
while rx.recv().is_ok() {
c += 1;
}
assert!(start.elapsed() < Duration::from_millis(4 * (tasks as u64)));
assert_eq!(c, tasks);
}
#[test]
fn drop_input_tx() {
let capacity = 10;
let (tx, rx, pool) = new_lambda_channel(Some(capacity), Some(capacity), None, simple_task);
assert_eq!(pool.set_pool_size(4), Ok(4));
for i in 0..(2 * capacity) {
tx.send(i as u32).unwrap();
}
sleep(Duration::from_millis(1));
// The 4 members are holding 4 values.
assert_eq!(tx.len(), 6);
assert!(rx.is_full());
// Test recruit while blocked.
assert_eq!(pool.set_pool_size(6), Ok(6));
sleep(Duration::from_millis(1));
// The 6 members are holding 6 values.
assert_eq!(tx.len(), 4);
assert!(rx.is_full());
drop(tx);
let mut c = 0usize;
while rx.recv().is_ok() {
c += 1;
}
assert_eq!(c, 2 * capacity);
}
#[test]
fn drop_output_rx() {
let capacity = 10;
let (tx, rx, pool) = new_lambda_channel(Some(capacity), Some(capacity), None, simple_task);
assert_eq!(pool.set_pool_size(4), Ok(4));
drop(rx);
let mut c = 0;
while tx.send(0).is_ok() {
c += 1;
}
assert_eq!(c, 0);
assert_eq!(tx.len(), c);
}
#[test]
fn thrash_pool_size() {
let tasks = 100usize;
let capacity = 10;
let (tx, rx, pool) = new_lambda_channel(Some(capacity), Some(capacity), None, simple_task);
assert_eq!(pool.set_pool_size(4), Ok(4));
spawn(move || {
for i in 0..tasks {
tx.send(i as u32).unwrap();
}
});
let mut c = 0;
while rx.recv().is_ok() {
c += 1;
if c >= 10 {
break;
}
}
assert_eq!(pool.set_pool_size(6), Ok(6));
while rx.recv().is_ok() {
c += 1;
if c >= 20 {
break;
}
}
assert_eq!(pool.set_pool_size(3), Ok(3));
while rx.recv().is_ok() {
c += 1;
if c >= 30 {
break;
}
}
assert_eq!(pool.set_pool_size(5), Ok(5));
sleep(Duration::from_millis(10));
assert_eq!(pool.set_pool_size(2), Ok(2));
while rx.recv().is_ok() {
c += 1;
if c >= 50 {
break;
}
}
assert_eq!(pool.set_pool_size(1), Ok(1));
while rx.recv().is_ok() {
c += 1;
}
assert_eq!(c, tasks);
}
}