1use reth_concurrency::sync::thread;
4
5#[doc(hidden)]
6pub use reth_concurrency::sync::Once;
7pub use thread_priority::{self, *};
8
9#[macro_export]
15macro_rules! once {
16 ($e:expr) => {{
17 static ONCE: $crate::utils::Once = $crate::utils::Once::new();
18 ONCE.call_once($e);
19 }};
20}
21
22pub fn increase_thread_priority() {
28 let thread_name = thread::current().name().unwrap_or("unnamed").to_string();
29 if let Err(err) = ThreadPriority::Max.set_for_current() {
30 tracing::debug!(%thread_name, ?err, "failed to set max thread priority, trying moderate bump; grant CAP_SYS_NICE to the process to enable this");
31 let fallback = ThreadPriority::Crossplatform(
33 ThreadPriorityValue::try_from(62u8).expect("62 is within the valid 0..100 range"),
34 );
35 if let Err(err) = fallback.set_for_current() {
36 tracing::debug!(%thread_name, ?err, "failed to set moderate thread priority");
37 }
38 }
39}
40
41#[allow(clippy::missing_const_for_fn)]
53pub fn deprioritize_background_threads() {
54 #[cfg(target_os = "linux")]
55 _deprioritize_background_threads();
56}
57
58#[cfg(target_os = "linux")]
63const DEPRIORITIZE_THREAD_PREFIXES: &[&str] = &["tracing-appende", "reqwest-interna"];
64
65#[cfg(target_os = "linux")]
66fn _deprioritize_background_threads() {
67 let pid = std::process::id();
68 let task_dir = format!("/proc/{pid}/task");
69
70 let entries = match std::fs::read_dir(&task_dir) {
71 Ok(entries) => entries,
72 Err(err) => {
73 tracing::debug!(%err, "failed to read /proc task directory");
74 return;
75 }
76 };
77
78 for entry in entries.filter_map(Result::ok) {
79 let tid_str = entry.file_name();
80 let Some(tid_str) = tid_str.to_str() else { continue };
81 let Ok(tid) = tid_str.parse::<i32>() else { continue };
82
83 let comm_path = format!("{task_dir}/{tid_str}/comm");
84 let comm = match std::fs::read_to_string(&comm_path) {
85 Ok(c) => c,
86 Err(_) => continue,
87 };
88 let comm = comm.trim();
89
90 if !DEPRIORITIZE_THREAD_PREFIXES.iter().any(|prefix| comm.starts_with(prefix)) {
91 continue;
92 }
93
94 unsafe {
98 let param = libc::sched_param { sched_priority: 0 };
99 if libc::sched_setscheduler(tid, libc::SCHED_IDLE, std::ptr::from_ref(¶m)) != 0 {
100 tracing::debug!(
101 tid,
102 comm,
103 err = std::io::Error::last_os_error().to_string(),
104 "failed to set SCHED_IDLE"
105 );
106 }
107 }
108
109 tracing::debug!(tid, comm, "deprioritized background thread (SCHED_IDLE)");
110 }
111}