monoio/utils/
bind_to_cpu_set.rs

1/// Bind error
2#[cfg(unix)]
3pub type BindError<T> = nix::Result<T>;
4
5/// Bind error
6#[cfg(windows)]
7pub type BindError<T> = std::io::Result<T>;
8
9/// Bind current thread to given cpus
10#[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "linux"))]
11pub fn bind_to_cpu_set(cpus: impl IntoIterator<Item = usize>) -> BindError<()> {
12    let mut cpuset = nix::sched::CpuSet::new();
13    for cpu in cpus {
14        cpuset.set(cpu)?;
15    }
16    let pid = nix::unistd::Pid::from_raw(0);
17    nix::sched::sched_setaffinity(pid, &cpuset)
18}
19
20/// Bind current thread to given cpus(but not works for non-linux)
21#[cfg(all(
22    unix,
23    not(any(target_os = "android", target_os = "dragonfly", target_os = "linux"))
24))]
25pub fn bind_to_cpu_set(_: impl IntoIterator<Item = usize>) -> BindError<()> {
26    Ok(())
27}
28
29/// Bind current thread to given cpus
30#[cfg(windows)]
31pub fn bind_to_cpu_set(_: impl IntoIterator<Item = usize>) -> BindError<()> {
32    Ok(())
33}
34
35#[cfg(all(test, feature = "utils"))]
36mod tests {
37    use super::*;
38
39    #[test]
40    fn bind_cpu() {
41        assert!(bind_to_cpu_set(Some(0)).is_ok());
42        #[cfg(all(
43            unix,
44            any(target_os = "android", target_os = "dragonfly", target_os = "linux")
45        ))]
46        assert!(bind_to_cpu_set(Some(100000)).is_err());
47    }
48}