iris_core/multicore/pin.rs
1use nix::sched::{sched_setaffinity, CpuSet};
2use nix::unistd::Pid;
3use nix::Error;
4
5/// Pins the current thread to a specific CPU core.
6///
7/// This function used the `sched_setaffinity` system call to restrict the current thread to
8/// execute only on the specified CPU core.
9///
10/// **Note:** This does *not* prevent other threads or processes from being scheduled on the same
11/// core. It only restricts where the current thread may run. To achieve true core exclusivity,
12/// other threads must be restricted separately.
13///
14/// # Arguments
15///
16/// * `core` - The CPU core number (0-indexed) to pin the thread to.
17///
18/// # Returns
19///
20/// * `Ok(())` - Thread successfully pinned to core.
21/// * `Err(Error)` - System called failed (invalid core, permissions, etc.)
22///
23/// # Platform Support
24///
25/// This function is Linux-specific and uses the `nix` crate's scheduler bindings.
26/// On systems without CPU affinity support, this function will return an error.
27pub fn pin_thread_to_core(core: u32) -> Result<(), Error> {
28 let mut cpu_set = CpuSet::new();
29 cpu_set.set(core as usize)?;
30 sched_setaffinity(Pid::from_raw(0), &cpu_set)?;
31 Ok(())
32}