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

rt: add runtime Id #5864

Merged
merged 5 commits into from Jul 19, 2023
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
32 changes: 32 additions & 0 deletions tokio/src/runtime/handle.rs
@@ -1,3 +1,5 @@
#[cfg(tokio_unstable)]
use crate::runtime;
use crate::runtime::{context, scheduler, RuntimeFlavor};

/// Handle to the runtime.
Expand Down Expand Up @@ -357,6 +359,36 @@ impl Handle {
scheduler::Handle::MultiThread(_) => RuntimeFlavor::MultiThread,
}
}

cfg_unstable! {
/// Returns the [`Id`] of the current `Runtime`.
///
/// # Examples
///
/// ```
/// use tokio::runtime::Handle;
///
/// #[tokio::main(flavor = "current_thread")]
/// async fn main() {
/// println!("Current runtime id: {}", Handle::current().id());
/// }
/// ```
///
/// **Note**: This is an [unstable API][unstable]. The public API of this type
/// may break in 1.x releases. See [the documentation on unstable
/// features][unstable] for details.
///
/// [unstable]: crate#unstable-features
/// [`Id`]: struct@crate::runtime::Id
pub fn id(&self) -> runtime::Id {
let owned_id = match &self.inner {
scheduler::Handle::CurrentThread(handle) => handle.owned_id(),
#[cfg(all(feature = "rt-multi-thread", not(tokio_wasi)))]
scheduler::Handle::MultiThread(handle) => handle.owned_id(),
};
owned_id.into()
}
}
}

cfg_metrics! {
Expand Down
46 changes: 46 additions & 0 deletions tokio/src/runtime/id.rs
Copy link
Contributor

Choose a reason for hiding this comment

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

Whether merge all taskid/threadid/runtimeid as one type id?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Keeping a separate type because we don't want users to be able to compare (for example) a task ID to a runtime ID. Also, the runtime::Id implementation is now pretty different as we're using the value from the (Local)OwnedTasks ID.

@@ -0,0 +1,46 @@
use std::fmt;
use std::num::NonZeroU64;

/// An opaque ID that uniquely identifies a runtime relative to all other currently
/// running runtimes.
///
/// # Notes
///
/// - Runtime IDs are unique relative to other *currently running* runtimes.
/// When a runtime completes, the same ID may be used for another runtime.
/// - Runtime IDs are *not* sequential, and do not indicate the order in which
/// runtimes are started or any other data.
/// - The runtime ID of the currently running task can be obtained from the
/// Handle.
///
/// # Examples
///
/// ```
/// use tokio::runtime::Handle;
///
/// #[tokio::main(flavor = "multi_thread", worker_threads = 4)]
/// async fn main() {
/// println!("Current runtime id: {}", Handle::current().id());
/// }
/// ```
///
/// **Note**: This is an [unstable API][unstable]. The public API of this type
/// may break in 1.x releases. See [the documentation on unstable
/// features][unstable] for details.
///
/// [unstable]: crate#unstable-features
#[cfg_attr(not(tokio_unstable), allow(unreachable_pub))]
#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq)]
pub struct Id(NonZeroU64);

impl From<NonZeroU64> for Id {
fn from(value: NonZeroU64) -> Self {
Id(value)
}
}

impl fmt::Display for Id {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
4 changes: 4 additions & 0 deletions tokio/src/runtime/mod.rs
Expand Up @@ -226,6 +226,10 @@ cfg_rt! {
mod builder;
pub use self::builder::Builder;
cfg_unstable! {
mod id;
#[cfg_attr(not(tokio_unstable), allow(unreachable_pub))]
pub use id::Id;

pub use self::builder::UnhandledPanic;
pub use crate::util::rand::RngSeed;
}
Expand Down
10 changes: 10 additions & 0 deletions tokio/src/runtime/scheduler/current_thread.rs
Expand Up @@ -541,6 +541,16 @@ cfg_metrics! {
}
}

cfg_unstable! {
use std::num::NonZeroU64;

impl Handle {
pub(crate) fn owned_id(&self) -> NonZeroU64 {
self.shared.owned.id
}
}
}

impl fmt::Debug for Handle {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_struct("current_thread::Handle { ... }").finish()
Expand Down
10 changes: 10 additions & 0 deletions tokio/src/runtime/scheduler/multi_thread/handle.rs
Expand Up @@ -59,6 +59,16 @@ impl Handle {
}
}

cfg_unstable! {
use std::num::NonZeroU64;

impl Handle {
pub(crate) fn owned_id(&self) -> NonZeroU64 {
self.shared.owned.id
}
}
}

impl fmt::Debug for Handle {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_struct("multi_thread::Handle { ... }").finish()
Expand Down
2 changes: 1 addition & 1 deletion tokio/src/runtime/scheduler/multi_thread/worker.rs
Expand Up @@ -158,7 +158,7 @@ pub(crate) struct Shared {
idle: Idle,

/// Collection of all active tasks spawned onto this executor.
pub(super) owned: OwnedTasks<Arc<Handle>>,
pub(crate) owned: OwnedTasks<Arc<Handle>>,

/// Data synchronized by the scheduler mutex
pub(super) synced: Mutex<Synced>,
Expand Down
4 changes: 2 additions & 2 deletions tokio/src/runtime/task/list.rs
Expand Up @@ -56,15 +56,15 @@ cfg_not_has_atomic_u64! {

pub(crate) struct OwnedTasks<S: 'static> {
inner: Mutex<CountedOwnedTasksInner<S>>,
id: NonZeroU64,
pub(crate) id: NonZeroU64,
}
struct CountedOwnedTasksInner<S: 'static> {
list: CountedLinkedList<Task<S>, <Task<S> as Link>::Target>,
closed: bool,
}
pub(crate) struct LocalOwnedTasks<S: 'static> {
inner: UnsafeCell<OwnedTasksInner<S>>,
id: NonZeroU64,
pub(crate) id: NonZeroU64,
_not_send_or_sync: PhantomData<*const ()>,
}
struct OwnedTasksInner<S: 'static> {
Expand Down
26 changes: 26 additions & 0 deletions tokio/src/task/local.rs
@@ -1,6 +1,8 @@
//! Runs `!Send` futures on the current thread.
use crate::loom::cell::UnsafeCell;
use crate::loom::sync::{Arc, Mutex};
#[cfg(tokio_unstable)]
use crate::runtime;
use crate::runtime::task::{self, JoinHandle, LocalOwnedTasks, Task};
use crate::runtime::{context, ThreadId};
use crate::sync::AtomicWaker;
Expand Down Expand Up @@ -785,6 +787,30 @@ cfg_unstable! {
.unhandled_panic = behavior;
self
}

/// Returns the [`Id`] of the current `LocalSet` runtime.
///
/// # Examples
///
/// ```rust
/// use tokio::task;
///
/// #[tokio::main]
/// async fn main() {
/// let local_set = task::LocalSet::new();
/// println!("Local set id: {}", local_set.id());
/// }
/// ```
///
/// **Note**: This is an [unstable API][unstable]. The public API of this type
/// may break in 1.x releases. See [the documentation on unstable
/// features][unstable] for details.
///
/// [unstable]: crate#unstable-features
/// [`Id`]: struct@crate::runtime::Id
pub fn id(&self) -> runtime::Id {
self.context.shared.local_state.owned.id.into()
}
}
}

Expand Down
23 changes: 23 additions & 0 deletions tokio/tests/rt_handle.rs
Expand Up @@ -60,6 +60,29 @@ fn interleave_then_enter() {
let _enter = rt3.enter();
}

#[cfg(tokio_unstable)]
mod unstable {
use super::*;

#[test]
fn runtime_id_is_same() {
let rt = rt();

let handle1 = rt.handle();
let handle2 = rt.handle();

assert_eq!(handle1.id(), handle2.id());
}

#[test]
fn runtime_ids_different() {
let rt1 = rt();
let rt2 = rt();

assert_ne!(rt1.handle().id(), rt2.handle().id());
}
}

fn rt() -> Runtime {
tokio::runtime::Builder::new_current_thread()
.build()
Expand Down
18 changes: 18 additions & 0 deletions tokio/tests/rt_threaded.rs
Expand Up @@ -762,4 +762,22 @@ mod unstable {
.unwrap();
})
}

#[test]
fn runtime_id_is_same() {
let rt = rt();

let handle1 = rt.handle();
let handle2 = rt.handle();

assert_eq!(handle1.id(), handle2.id());
}

#[test]
fn runtime_ids_different() {
let rt1 = rt();
let rt2 = rt();

assert_ne!(rt1.handle().id(), rt2.handle().id());
}
}