use std::io;
#[cfg(any(
target_os = "linux",
target_os = "android",
target_os = "macos",
target_os = "ios"
))]
#[allow(unsafe_code)]
pub(super) fn lower_current_thread_priority() -> io::Result<()> {
let thread = unsafe { libc::pthread_self() };
let mut policy = 0;
let mut parameters: libc::sched_param = unsafe { std::mem::zeroed() };
let error = unsafe { libc::pthread_getschedparam(thread, &mut policy, &mut parameters) };
if error != 0 {
return Err(io::Error::from_raw_os_error(error));
}
let minimum = unsafe { libc::sched_get_priority_min(policy) };
if minimum == -1 {
return Err(io::Error::last_os_error());
}
parameters.sched_priority = minimum;
let error = unsafe { libc::pthread_setschedparam(thread, policy, ¶meters) };
if error != 0 {
return Err(io::Error::from_raw_os_error(error));
}
#[cfg(any(target_os = "linux", target_os = "android"))]
if matches!(
policy,
libc::SCHED_OTHER | libc::SCHED_BATCH | libc::SCHED_IDLE
) {
let niceness = if policy == libc::SCHED_IDLE { 0 } else { 19 };
if unsafe { libc::setpriority(libc::PRIO_PROCESS, 0, niceness) } != 0 {
return Err(io::Error::last_os_error());
}
}
Ok(())
}
#[cfg(windows)]
#[allow(unsafe_code)]
pub(super) fn lower_current_thread_priority() -> io::Result<()> {
use windows_sys::Win32::System::Threading::{
GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_LOWEST,
};
if unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST) } == 0 {
return Err(io::Error::last_os_error());
}
Ok(())
}
#[cfg(not(any(
target_os = "linux",
target_os = "android",
target_os = "macos",
target_os = "ios",
windows
)))]
pub(super) fn lower_current_thread_priority() -> io::Result<()> {
Err(io::Error::new(
io::ErrorKind::Unsupported,
"lowering miner thread priority is unsupported on this platform",
))
}