-
-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathspawn.rs
63 lines (58 loc) · 1.62 KB
/
spawn.rs
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
#[cfg(all(unix, feature = "backtrace"))]
pub use backtrace_on_stack_overflow;
use std::thread::{self, JoinHandle};
#[cfg(all(windows, feature = "backtrace"))]
pub use w_boson;
const STACK_SIZE: usize = if cfg!(feature = "large_thread") {
16 * 1024 * 1024
} else {
8 * 1024 * 1024
};
#[macro_export]
macro_rules! enable_overflow_stacktrace {
() => {
#[cfg(all(unix, feature = "backtrace"))]
unsafe {
$crate::spawn::backtrace_on_stack_overflow::enable()
};
#[cfg(all(windows, feature = "backtrace"))]
unsafe {
$crate::spawn::w_boson::enable()
};
};
}
/// Execute the function in a new thread.
/// The default stack size is 4MB, and with the `large_thread` flag, the stack size is 8MB.
pub fn exec_new_thread<F, T>(run: F, name: &str) -> T
where
F: FnOnce() -> T + Send + 'static,
T: Send + 'static,
{
enable_overflow_stacktrace!();
let child = thread::Builder::new()
.name(name.to_string())
.stack_size(STACK_SIZE)
.spawn(run)
.unwrap();
// Wait for thread to join
child.join().unwrap_or_else(|err| {
eprintln!("Thread panicked: {err:?}");
std::process::exit(1);
})
}
pub fn spawn_new_thread<F, T>(run: F, name: &str) -> JoinHandle<T>
where
F: FnOnce() -> T + Send + 'static,
T: Send + 'static,
{
enable_overflow_stacktrace!();
thread::Builder::new()
.name(name.to_string())
.stack_size(STACK_SIZE)
.spawn(run)
.unwrap()
}
pub fn safe_yield() {
std::thread::yield_now();
std::thread::sleep(std::time::Duration::from_millis(10));
}