use super::worker::ThreadId;
use crate::util::options::AffinityKind;
#[cfg(target_os = "linux")]
use libc::{cpu_set_t, sched_getaffinity, sched_setaffinity, CPU_COUNT, CPU_SET, CPU_ZERO};
pub type CoreId = u16;
#[cfg(target_os = "linux")]
pub fn get_total_num_cpus() -> u16 {
use std::mem::MaybeUninit;
unsafe {
let mut cs = MaybeUninit::zeroed().assume_init();
CPU_ZERO(&mut cs);
sched_getaffinity(0, std::mem::size_of::<cpu_set_t>(), &mut cs);
CPU_COUNT(&cs) as u16
}
}
#[cfg(not(target_os = "linux"))]
pub fn get_total_num_cpus() -> u16 {
unimplemented!()
}
impl AffinityKind {
pub fn resolve_affinity(&self, thread: ThreadId) {
match self {
AffinityKind::OsDefault => {}
AffinityKind::RoundRobin(cpuset) => {
let cpu = cpuset[thread % cpuset.len()];
debug!("Set affinity for thread {} to core {}", thread, cpu);
bind_current_thread_to_core(cpu);
}
}
}
}
#[cfg(target_os = "linux")]
fn bind_current_thread_to_core(cpu: CoreId) {
use std::mem::MaybeUninit;
unsafe {
let mut cs = MaybeUninit::zeroed().assume_init();
CPU_ZERO(&mut cs);
CPU_SET(cpu as usize, &mut cs);
sched_setaffinity(0, std::mem::size_of::<cpu_set_t>(), &cs);
}
}
#[cfg(not(target_os = "linux"))]
fn bind_current_thread_to_core(_cpu: CoreId) {
unimplemented!()
}