@@ -3,11 +3,60 @@ use std::ops::Deref;
3
3
4
4
pub struct ThreadAbstraction ( Option < JoinHandle < ( ) > > ) ;
5
5
6
+ /// Schrödinger's threads.
7
+ ///
8
+ /// Threads in ThreadAbstraction can be either be started or not started, via the `spawn_if`
9
+ /// method.
10
+ ///
11
+ /// # Why?
12
+ ///
13
+ /// This exists due to a dilemma Encore once had, it boils down to this:
14
+ ///
15
+ /// 1. Spawn thread
16
+ /// 1. Thread (usually with a compile time cfg!) checks if said feature is enabled
17
+ /// 1. Worst case, thread immedately `return`s
18
+ /// 1. Thread ends up being spawned, resulting in an additonal syscall, and possibly increased
19
+ /// binary size
20
+ ///
21
+ /// Instead, ThreadAbstraction prevents the thread from starting if a compile time condition says
22
+ /// so, but still allows regular ol `spawn`ing of threads.
23
+ ///
24
+ /// # Disadvantages
25
+ ///
26
+ /// It does not provide full `JoinThread<T>` parity. Only few methods are implemented.
6
27
impl ThreadAbstraction {
28
+ /// Spawn a thread.
29
+ ///
30
+ /// Feels exactly the same as `std::thread::spawn()`, but returns a ThreadAbstraction. It does
31
+ /// not provide full `JoinThread<T>` parity.
32
+ ///
33
+ /// # Example
34
+ ///
35
+ /// ```rust
36
+ /// spawn(move || { println!("this will run!") });
37
+ /// ```
7
38
pub fn spawn < F : std:: marker:: Send + FnOnce ( ) + ' static > ( f : F ) -> ThreadAbstraction {
8
39
ThreadAbstraction ( Some ( spawn ( f) ) )
9
40
}
10
41
42
+ /// Spawns a thread if a condition is true.
43
+ ///
44
+ /// Almost the same as `std::thread::spawn()`, but you need to provide a bool. No thread will
45
+ /// be started if such bool is `false`.
46
+ ///
47
+ /// # Examples
48
+ ///
49
+ /// ```rust
50
+ /// spawn_if(move || { println!("this will run!") }, true);
51
+ /// ```
52
+ ///
53
+ /// ```rust
54
+ /// spawn_if(move || { println!("this will not run!") }, false);
55
+ /// ```
56
+ ///
57
+ /// ```rust
58
+ /// spawn_if(move || { println!("this will only run if built in debug!"); }, cfg!(debug_assertions));
59
+ /// ```
11
60
pub fn spawn_if < F : std:: marker:: Send + FnOnce ( ) + ' static > ( f : F , condition : bool ) -> ThreadAbstraction {
12
61
if condition {
13
62
ThreadAbstraction ( Some ( spawn ( f) ) )
@@ -16,6 +65,16 @@ impl ThreadAbstraction {
16
65
}
17
66
}
18
67
68
+ /// Wait for thread to finish
69
+ ///
70
+ /// If a thread is not started (see `spawn_if`), it will return immedately, otherwise, it will
71
+ /// block the current thread otherwise. It works _very similarly_ to `JoinThread.join()`, but
72
+ /// it will not return anything.
73
+ ///
74
+ /// # Panics
75
+ ///
76
+ /// In debug builds, if a thread panics, the value will be unwrapped. It will not panic in
77
+ /// release builds
19
78
pub fn join ( self ) {
20
79
if self . 0 . is_some ( ) {
21
80
if cfg ! ( debug_assertions) {
0 commit comments