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

Partially implement thread scheduling attributes API proposal #101222

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions library/std/src/os/horizon/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@

pub mod fs;
pub(crate) mod raw;
pub mod thread;
59 changes: 59 additions & 0 deletions library/std/src/os/horizon/thread.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
//! Horizon-specific extensions for working with the [`std::thread`] module.
//!
//! [`std::thread`]: crate::thread

#![unstable(feature = "thread_scheduling", issue = "none")]

use crate::fmt;

/// The relative priority of the thread. See the `libctru` docs for the `prio`
/// parameter of [`threadCreate`] for details on valid values.
///
/// [`threadCreate`]: https://libctru.devkitpro.org/thread_8h.html#a38c873d8cb02de7f5eca848fe68183ee
pub struct Priority(pub(crate) libc::c_int);

impl TryFrom<i32> for Priority {
type Error = ();

fn try_from(value: i32) -> Result<Self, Self::Error> {
match value {
0x18..=0x3F => Ok(Self(value)),
_ => Err(()),
}
}
}

impl crate::fmt::Debug for Priority {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Priority").finish_non_exhaustive()
}
}

/// The CPU(s) on which to spawn the thread. See the `libctru` docs for the
/// `core_id` parameter of [`threadCreate`] for details on valid values.
///
/// [`threadCreate`]: https://libctru.devkitpro.org/thread_8h.html#a38c873d8cb02de7f5eca848fe68183ee
pub struct Affinity(pub(crate) libc::c_int);

impl Default for Affinity {
fn default() -> Self {
Self(-2)
}
}

impl TryFrom<i32> for Affinity {
type Error = ();

fn try_from(value: i32) -> Result<Self, Self::Error> {
match value {
-2..=4 => Ok(Self(value)),
_ => Err(()),
}
}
}

impl crate::fmt::Debug for Affinity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Affinity").finish_non_exhaustive()
}
}
1 change: 1 addition & 0 deletions library/std/src/os/linux/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ pub mod fs;
pub mod net;
pub mod process;
pub mod raw;
pub mod thread;
66 changes: 66 additions & 0 deletions library/std/src/os/linux/thread.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
//! Linux-specific extensions for working with the [`std::thread`] module.
//!
//! [`std::thread`]: crate::thread

#![unstable(feature = "thread_scheduling", issue = "none")]

use crate::fmt;

/// The relative scheduling priority of a thread, corresponding to the
/// `sched_priority` scheduling parameter.
///
/// Refer to the man page for [`pthread_attr_setschedparam(3)`] for more details.
///
/// [`pthread_attr_setschedparam(3)`]: https://man7.org/linux/man-pages/man3/pthread_attr_setschedparam.3.html
pub struct Priority(pub(crate) libc::c_int);

impl Priority {
/// Create an integer priority.
pub fn new(priority: i32) -> Self {
Self(priority)
}
}

impl crate::fmt::Debug for Priority {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Priority").finish_non_exhaustive()
}
}

/// The CPU affinity mask of a thread, which determines what CPUs a thread is
/// eligible to run on.
///
/// Refer to the man page for [`pthread_attr_setaffinity_np(3)`] for more details.
///
/// [`pthread_attr_setaffinity_np(3)`]: https://man7.org/linux/man-pages/man3/pthread_attr_setaffinity_np.3.html
pub struct Affinity(pub(crate) libc::cpu_set_t);

impl Affinity {
/// Create an affinity mask with no CPUs in it.
/// See the man page entry for [`CPU_ZERO`] for more details.
///
/// [`CPU_ZERO`]: https://man7.org/linux/man-pages/man3/CPU_SET.3.html
pub fn new() -> Self {
unsafe {
let mut set = crate::mem::zeroed();
libc::CPU_ZERO(&mut set);
Self(set)
}
}

/// Add a CPU to the affinity mask.
/// See the man page entry for [`CPU_SET`] for more details.
///
/// [`CPU_SET`]: https://man7.org/linux/man-pages/man3/CPU_SET.3.html
pub fn set(&mut self, cpu: usize) {
unsafe {
libc::CPU_SET(cpu, &mut self.0);
}
}
}

impl crate::fmt::Debug for Affinity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Affinity").finish_non_exhaustive()
}
}
10 changes: 9 additions & 1 deletion library/std/src/sys/hermit/thread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use crate::mem;
use crate::num::NonZeroUsize;
use crate::sys::hermit::abi;
use crate::sys::hermit::thread_local_dtor::run_dtors;
use crate::thread::NativeOptions;
use crate::time::Duration;

pub type Tid = abi::Tid;
Expand Down Expand Up @@ -55,7 +56,11 @@ impl Thread {
}
}

pub unsafe fn new(stack: usize, p: Box<dyn FnOnce()>) -> io::Result<Thread> {
pub unsafe fn new(
stack: usize,
p: Box<dyn FnOnce()>,
_native_options: NativeOptions,
) -> io::Result<Thread> {
Thread::new_with_coreid(stack, p, -1 /* = no specific core */)
}

Expand Down Expand Up @@ -97,6 +102,9 @@ impl Thread {
}
}

pub type Priority = ();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These should be structs instead of type definitions in case this is implemented for the target in the future.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since this is a private type, I think it should be possible to change its type freely without any consequences to user code (alias or otherwise). However if it was re-exported as pub (per your other comment) then I agree it would be better as struct Priority(())

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah yeah, this is sys and not actually public

pub type Affinity = ();

pub fn available_parallelism() -> io::Result<NonZeroUsize> {
unsupported()
}
Expand Down
10 changes: 9 additions & 1 deletion library/std/src/sys/itron/thread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use crate::{
mem::ManuallyDrop,
sync::atomic::{AtomicUsize, Ordering},
sys::thread_local_dtor::run_dtors,
thread::NativeOptions,
time::Duration,
};

Expand Down Expand Up @@ -83,7 +84,11 @@ impl Thread {
/// # Safety
///
/// See `thread::Builder::spawn_unchecked` for safety requirements.
pub unsafe fn new(stack: usize, p: Box<dyn FnOnce()>) -> io::Result<Thread> {
pub unsafe fn new(
stack: usize,
p: Box<dyn FnOnce()>,
_native_options: NativeOptions,
) -> io::Result<Thread> {
let inner = Box::new(ThreadInner {
start: UnsafeCell::new(ManuallyDrop::new(p)),
lifecycle: AtomicUsize::new(LIFECYCLE_INIT),
Expand Down Expand Up @@ -288,6 +293,9 @@ impl Drop for Thread {
}
}

pub type Priority = ();
pub type Affinity = ();

pub mod guard {
pub type Guard = !;
pub unsafe fn current() -> Option<Guard> {
Expand Down
10 changes: 9 additions & 1 deletion library/std/src/sys/sgx/thread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use super::unsupported;
use crate::ffi::CStr;
use crate::io;
use crate::num::NonZeroUsize;
use crate::thread::NativeOptions;
use crate::time::Duration;

use super::abi::usercalls;
Expand Down Expand Up @@ -104,7 +105,11 @@ pub mod wait_notify {

impl Thread {
// unsafe: see thread::Builder::spawn_unchecked for safety requirements
pub unsafe fn new(_stack: usize, p: Box<dyn FnOnce()>) -> io::Result<Thread> {
pub unsafe fn new(
_stack: usize,
p: Box<dyn FnOnce()>,
_native_options: NativeOptions,
) -> io::Result<Thread> {
let mut queue_lock = task_queue::lock();
unsafe { usercalls::launch_thread()? };
let (task, handle) = task_queue::Task::new(p);
Expand Down Expand Up @@ -137,6 +142,9 @@ impl Thread {
}
}

pub type Priority = ();
pub type Affinity = ();

pub fn available_parallelism() -> io::Result<NonZeroUsize> {
unsupported()
}
Expand Down
46 changes: 44 additions & 2 deletions library/std/src/sys/unix/thread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,19 @@ pub const DEFAULT_MIN_STACK_SIZE: usize = 256 * 1024;
#[cfg(target_os = "espidf")]
pub const DEFAULT_MIN_STACK_SIZE: usize = 0; // 0 indicates that the stack size configured in the ESP-IDF menuconfig system should be used

cfg_if::cfg_if! {
if #[cfg(target_os = "horizon")] {
pub type Priority = crate::os::horizon::thread::Priority;
pub type Affinity = crate::os::horizon::thread::Affinity;
} else if #[cfg(target_os = "linux")] {
pub type Priority = crate::os::linux::thread::Priority;
pub type Affinity = crate::os::linux::thread::Affinity;
} else {
pub type Priority = ();
pub type Affinity = ();
}
}

#[cfg(target_os = "fuchsia")]
mod zircon {
type zx_handle_t = u32;
Expand Down Expand Up @@ -48,7 +61,11 @@ unsafe impl Sync for Thread {}

impl Thread {
// unsafe: see thread::Builder::spawn_unchecked for safety requirements
pub unsafe fn new(stack: usize, p: Box<dyn FnOnce()>) -> io::Result<Thread> {
pub(crate) unsafe fn new(
stack: usize,
p: Box<dyn FnOnce()>,
#[allow(unused)] native_options: crate::thread::NativeOptions,
) -> io::Result<Thread> {
let p = Box::into_raw(box p);
let mut native: libc::pthread_t = mem::zeroed();
let mut attr: libc::pthread_attr_t = mem::zeroed();
Expand Down Expand Up @@ -84,6 +101,30 @@ impl Thread {
};
}

#[cfg(any(target_os = "linux", target_os = "horizon"))]
{
if let Some(priority) = native_options.priority {
let _sched_param = libc::sched_param { sched_priority: priority.0 };
todo!("needs libc support for pthread_attr_setschedparam")
// assert_eq!(libc::pthread_attr_setschedparam(&mut attr, &sched_param), 0);
}

if let Some(affinity) = native_options.affinity {
#[cfg(target_os = "linux")]
assert_eq!(
libc::pthread_attr_setaffinity_np(
&mut attr,
mem::size_of::<libc::cpu_set_t>(),
&affinity.0,
),
0
);

#[cfg(target_os = "horizon")]
assert_eq!(libc::pthread_attr_setprocessorid_np(&mut attr, affinity.0), 0);
}
}

let ret = libc::pthread_create(&mut native, &attr, thread_start, p as *mut _);
// Note: if the thread creation fails and this assert fails, then p will
// be leaked. However, an alternative design could cause double-free
Expand Down Expand Up @@ -213,7 +254,8 @@ impl Thread {
target_os = "l4re",
target_os = "emscripten",
target_os = "redox",
target_os = "vxworks"
target_os = "vxworks",
target_os = "horizon"
))]
pub fn set_name(_name: &CStr) {
// Newlib, Emscripten, and VxWorks have no way to set a thread name.
Expand Down
10 changes: 9 additions & 1 deletion library/std/src/sys/unsupported/thread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use super::unsupported;
use crate::ffi::CStr;
use crate::io;
use crate::num::NonZeroUsize;
use crate::thread::NativeOptions;
use crate::time::Duration;

pub struct Thread(!);
Expand All @@ -10,7 +11,11 @@ pub const DEFAULT_MIN_STACK_SIZE: usize = 4096;

impl Thread {
// unsafe: see thread::Builder::spawn_unchecked for safety requirements
pub unsafe fn new(_stack: usize, _p: Box<dyn FnOnce()>) -> io::Result<Thread> {
pub unsafe fn new(
_stack: usize,
_p: Box<dyn FnOnce()>,
_native_options: NativeOptions,
) -> io::Result<Thread> {
unsupported()
}

Expand All @@ -31,6 +36,9 @@ impl Thread {
}
}

pub type Priority = ();
pub type Affinity = ();

pub fn available_parallelism() -> io::Result<NonZeroUsize> {
unsupported()
}
Expand Down
10 changes: 9 additions & 1 deletion library/std/src/sys/wasi/thread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use crate::io;
use crate::mem;
use crate::num::NonZeroUsize;
use crate::sys::unsupported;
use crate::thread::NativeOptions;
use crate::time::Duration;

pub struct Thread(!);
Expand All @@ -13,7 +14,11 @@ pub const DEFAULT_MIN_STACK_SIZE: usize = 4096;

impl Thread {
// unsafe: see thread::Builder::spawn_unchecked for safety requirements
pub unsafe fn new(_stack: usize, _p: Box<dyn FnOnce()>) -> io::Result<Thread> {
pub unsafe fn new(
_stack: usize,
_p: Box<dyn FnOnce()>,
_native_options: NativeOptions,
) -> io::Result<Thread> {
unsupported()
}

Expand Down Expand Up @@ -66,6 +71,9 @@ impl Thread {
}
}

pub type Priority = ();
pub type Affinity = ();

pub fn available_parallelism() -> io::Result<NonZeroUsize> {
unsupported()
}
Expand Down
10 changes: 9 additions & 1 deletion library/std/src/sys/wasm/atomics/thread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::ffi::CStr;
use crate::io;
use crate::num::NonZeroUsize;
use crate::sys::unsupported;
use crate::thread::NativeOptions;
use crate::time::Duration;

pub struct Thread(!);
Expand All @@ -10,7 +11,11 @@ pub const DEFAULT_MIN_STACK_SIZE: usize = 4096;

impl Thread {
// unsafe: see thread::Builder::spawn_unchecked for safety requirements
pub unsafe fn new(_stack: usize, _p: Box<dyn FnOnce()>) -> io::Result<Thread> {
pub unsafe fn new(
_stack: usize,
_p: Box<dyn FnOnce()>,
_native_options: NativeOptions,
) -> io::Result<Thread> {
unsupported()
}

Expand Down Expand Up @@ -40,6 +45,9 @@ impl Thread {
pub fn join(self) {}
}

pub type Priority = ();
pub type Affinity = ();

pub fn available_parallelism() -> io::Result<NonZeroUsize> {
unsupported()
}
Expand Down
Loading