Skip to content

Commit

Permalink
make task_id_counter thread local in loom tests
Browse files Browse the repository at this point in the history
  • Loading branch information
wathenjiang committed Sep 28, 2023
1 parent 58135de commit ca60be6
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
16 changes: 16 additions & 0 deletions tokio/src/runtime/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ use std::cell::Cell;
#[cfg(any(feature = "rt", feature = "macros"))]
use crate::util::rand::FastRand;

#[cfg(loom)]
use crate::loom::sync::atomic::StaticAtomicU64;
cfg_rt! {
mod blocking;
pub(crate) use blocking::{disallow_block_in_place, try_enter_blocking_region, BlockingRegionGuard};
Expand Down Expand Up @@ -72,6 +74,10 @@ struct Context {
any(target_arch = "aarch64", target_arch = "x86", target_arch = "x86_64")
))]
trace: trace::Context,

/// In loom tests, we make task_id_counter in thread local for ensuring each loom thread is deterministic
#[cfg(loom)]
task_id_counter: StaticAtomicU64,
}

tokio_thread_local! {
Expand Down Expand Up @@ -117,6 +123,8 @@ tokio_thread_local! {
)
))]
trace: trace::Context::new(),
#[cfg(loom)]
task_id_counter: StaticAtomicU64::new(1),
}
}
}
Expand All @@ -135,6 +143,14 @@ pub(super) fn budget<R>(f: impl FnOnce(&Cell<coop::Budget>) -> R) -> Result<R, A
CONTEXT.try_with(|ctx| f(&ctx.budget))
}

#[cfg(loom)]
pub(super) fn next_task_id() -> Result<u64, AccessError> {
CONTEXT.try_with(|ctx| {
ctx.task_id_counter
.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
})
}

cfg_rt! {
use crate::runtime::ThreadId;

Expand Down
12 changes: 9 additions & 3 deletions tokio/src/runtime/task/id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,11 +74,17 @@ impl fmt::Display for Id {

impl Id {
pub(crate) fn next() -> Self {
use crate::loom::sync::atomic::{Ordering::Relaxed, StaticAtomicU64};
#[cfg(loom)]
return Self(context::next_task_id().unwrap());

static NEXT_ID: StaticAtomicU64 = StaticAtomicU64::new(1);
#[cfg(not(loom))]
{
use crate::loom::sync::atomic::{Ordering::Relaxed, StaticAtomicU64};

Self(NEXT_ID.fetch_add(1, Relaxed))
static NEXT_ID: StaticAtomicU64 = StaticAtomicU64::new(1);

Self(NEXT_ID.fetch_add(1, Relaxed))
}
}

pub(crate) fn as_u64(&self) -> u64 {
Expand Down

0 comments on commit ca60be6

Please sign in to comment.