|
| 1 | +use std::fmt; |
| 2 | + |
| 3 | +/// An opaque ID that uniquely identifies a runtime relative to all other currently |
| 4 | +/// running runtimes. |
| 5 | +/// |
| 6 | +/// # Notes |
| 7 | +/// |
| 8 | +/// - Runtime IDs are unique relative to other *currently running* runtimes. |
| 9 | +/// When a task completes, the same ID may be used for another task. |
| 10 | +/// - Runtime IDs are *not* sequential, and do not indicate the order in which |
| 11 | +/// runtimes are started or any other data. |
| 12 | +/// - The runtime ID of the currently running task can be obtained from the |
| 13 | +/// Handle. |
| 14 | +/// |
| 15 | +/// # Examples |
| 16 | +/// |
| 17 | +/// ``` |
| 18 | +/// use tokio::runtime::Handle; |
| 19 | +/// |
| 20 | +/// #[tokio::main(flavor = "multi_thread", worker_threads = 4)] |
| 21 | +/// async fn main() { |
| 22 | +/// println!("Current runtime id: {}", Handle::current().id()); |
| 23 | +/// } |
| 24 | +/// ``` |
| 25 | +/// |
| 26 | +/// **Note**: This is an [unstable API][unstable]. The public API of this type |
| 27 | +/// may break in 1.x releases. See [the documentation on unstable |
| 28 | +/// features][unstable] for details. |
| 29 | +/// |
| 30 | +/// [unstable]: crate#unstable-features |
| 31 | +#[cfg_attr(not(tokio_unstable), allow(unreachable_pub))] |
| 32 | +#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq)] |
| 33 | +pub struct Id(u64); |
| 34 | + |
| 35 | +impl fmt::Display for Id { |
| 36 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 37 | + self.0.fmt(f) |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +impl Id { |
| 42 | + pub(crate) fn next() -> Self { |
| 43 | + use crate::loom::sync::atomic::{Ordering::Relaxed, StaticAtomicU64}; |
| 44 | + |
| 45 | + static NEXT_ID: StaticAtomicU64 = StaticAtomicU64::new(1); |
| 46 | + |
| 47 | + Self(NEXT_ID.fetch_add(1, Relaxed)) |
| 48 | + } |
| 49 | +} |
0 commit comments