Skip to content

Commit

Permalink
Fix mapping of Crossplatform Priority to Linux Nice (#32)
Browse files Browse the repository at this point in the history
  • Loading branch information
arthurprs committed Oct 11, 2023
1 parent 4b6d204 commit 6f980a9
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/unix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -413,8 +413,10 @@ impl ThreadPriority {
Self::to_allowed_value_for_policy(p as i32, policy).map(|v| v as u32)
}
ThreadSchedulePolicy::Normal(_) => {
// Mapping a [0..100] priority into niceness [-20..20] needs reversing the ratio,
// as the lowest nice is actually the highest priority.
let niceness_values = NICENESS_MAX.abs() + NICENESS_MIN.abs();
let ratio = p as f32 / ThreadPriorityValue::MAX as f32;
let ratio = 1f32 - (p as f32 / ThreadPriorityValue::MAX as f32);
let niceness = ((niceness_values as f32 * ratio) as i8 + NICENESS_MAX) as i32;
Self::to_allowed_value_for_policy(niceness, policy).map(|v| v as u32)
}
Expand Down
16 changes: 16 additions & 0 deletions tests/unix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,22 @@ use rstest::rstest;
use std::convert::TryInto;
use thread_priority::*;

#[cfg(target_os = "linux")]
#[test]
fn get_and_set_priority_with_normal_and_crossplatform() {
let nice = unsafe { libc::getpriority(0, 0) };
assert_eq!(nice, 0);
crate::set_current_thread_priority(ThreadPriority::Crossplatform(30u8.try_into().unwrap()))
.unwrap();
let nice = unsafe { libc::getpriority(0, 0) };
assert!(nice > 0);
// Note that increasing priority requires extra permissions (e.g. sudo)
crate::set_current_thread_priority(ThreadPriority::Crossplatform(70u8.try_into().unwrap()))
.unwrap();
let nice = unsafe { libc::getpriority(0, 0) };
assert!(nice < 0);
}

#[cfg(target_os = "linux")]
#[rstest]
fn get_and_set_priority_with_normal_policies(
Expand Down

0 comments on commit 6f980a9

Please sign in to comment.