Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a sched_getcpu wrapper #1825

Merged
merged 1 commit into from Sep 27, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Expand Up @@ -6,6 +6,8 @@ This project adheres to [Semantic Versioning](https://semver.org/).
## [Unreleased] - ReleaseDate
### Added

- Added `sched_getcpu` on platforms that support it.
([#1825](https://github.com/nix-rust/nix/pull/1825))
- Added `sched_getaffinity` and `sched_setaffinity` on FreeBSD.
([#1804](https://github.com/nix-rust/nix/pull/1804))
- Added `line_discipline` field to `Termios` on Linux, Android and Haiku
Expand Down
7 changes: 7 additions & 0 deletions src/sched.rs
Expand Up @@ -290,6 +290,13 @@ mod sched_affinity {

Errno::result(res).and(Ok(cpuset))
}

/// Determines the CPU on which the calling thread is running.
pub fn sched_getcpu() -> Result<usize> {
let res = unsafe { libc::sched_getcpu() };

Errno::result(res).map(|int| int as usize)
}
}

/// Explicitly yield the processor to other threads.
Expand Down
6 changes: 5 additions & 1 deletion test/test_sched.rs
@@ -1,4 +1,4 @@
use nix::sched::{sched_getaffinity, sched_setaffinity, CpuSet};
use nix::sched::{sched_getaffinity, sched_getcpu, sched_setaffinity, CpuSet};
use nix::unistd::Pid;

#[test]
Expand Down Expand Up @@ -30,6 +30,10 @@ fn test_sched_affinity() {
)
}

// Now check that we're also currently running on the CPU in question.
let cur_cpu = sched_getcpu().unwrap();
assert_eq!(cur_cpu, last_valid_cpu);

// Finally, reset the initial CPU set
sched_setaffinity(Pid::from_raw(0), &initial_affinity).unwrap();
}