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

Using sharded locks instead of a global lock for Timers #6534

Merged
merged 33 commits into from
May 22, 2024
Merged
Show file tree
Hide file tree
Changes from 23 commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
ee626f5
first commit
wathenjiang May 3, 2024
ed42fae
fix args in build_alt_threaded_runtime
wathenjiang May 4, 2024
1915c57
fix ci
wathenjiang May 4, 2024
3f9a443
adopt code review suggestions from FrankReh
wathenjiang May 4, 2024
5954e4f
fix set_next_wake_up&& small refactor
wathenjiang May 5, 2024
565432b
thread-local id
wathenjiang May 5, 2024
71bb30c
use crate::runtime::context::thread_rng_n
wathenjiang May 5, 2024
8bf56ca
rm feature
wathenjiang May 5, 2024
e4288c6
fix multi_thread_alt
wathenjiang May 5, 2024
7cdddd6
ci: allow(dead_code)
wathenjiang May 5, 2024
178baeb
ci: rustfmt
wathenjiang May 5, 2024
2de08f2
fix: condition feature
wathenjiang May 5, 2024
c808e81
fix: ci
wathenjiang May 5, 2024
11ce15a
use cfg_rt and cfg_not_rt
wathenjiang May 5, 2024
1d309bf
add time feature
wathenjiang May 5, 2024
256c279
add time feature again
wathenjiang May 5, 2024
6c8aa23
do not use random in context when shutdown
wathenjiang May 5, 2024
1fb35c9
add time feature
wathenjiang May 5, 2024
2497479
fix time feature
wathenjiang May 5, 2024
18dd900
use context::thread_rng_n
wathenjiang May 5, 2024
fea8e32
feat: try to avoid lock in clear_entry
wathenjiang May 14, 2024
5ecfd75
revert head
wathenjiang May 14, 2024
f7b36cb
Merge branch 'master' into sharded-timer
wathenjiang May 16, 2024
16ff7ae
style: rename get_shard_id method to generate_shard_id function
wathenjiang May 17, 2024
b5d8ca1
fix: change shard_size type from usize to u32
wathenjiang May 17, 2024
ba8fc74
rm the unnecessary mold operation
wathenjiang May 17, 2024
4a2c88e
Update tokio/src/runtime/time/entry.rs
wathenjiang May 20, 2024
c069805
feat: add AtomicOptionNonZeroU64 helper type
wathenjiang May 20, 2024
5e3d1b5
fix: ci
wathenjiang May 20, 2024
8ca8ddb
fix: next_wake shoud be in new method
wathenjiang May 20, 2024
0c408f0
add the helper next_wake_time function
wathenjiang May 21, 2024
71fd4ff
Update tokio/src/runtime/scheduler/multi_thread_alt/worker.rs
Darksonn May 22, 2024
b687274
Merge branch 'master' into sharded-timer
Darksonn May 22, 2024
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
9 changes: 5 additions & 4 deletions tokio/src/runtime/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -702,7 +702,7 @@ impl Builder {
}
}

fn get_cfg(&self) -> driver::Cfg {
fn get_cfg(&self, workers: usize) -> driver::Cfg {
driver::Cfg {
enable_pause_time: match self.kind {
Kind::CurrentThread => true,
Expand All @@ -715,6 +715,7 @@ impl Builder {
enable_time: self.enable_time,
start_paused: self.start_paused,
nevents: self.nevents,
workers,
}
}

Expand Down Expand Up @@ -1095,7 +1096,7 @@ impl Builder {
use crate::runtime::scheduler::{self, CurrentThread};
use crate::runtime::{runtime::Scheduler, Config};

let (driver, driver_handle) = driver::Driver::new(self.get_cfg())?;
let (driver, driver_handle) = driver::Driver::new(self.get_cfg(1))?;

// Blocking pool
let blocking_pool = blocking::create_blocking_pool(self, self.max_blocking_threads);
Expand Down Expand Up @@ -1248,7 +1249,7 @@ cfg_rt_multi_thread! {

let core_threads = self.worker_threads.unwrap_or_else(num_cpus);

let (driver, driver_handle) = driver::Driver::new(self.get_cfg())?;
let (driver, driver_handle) = driver::Driver::new(self.get_cfg(core_threads))?;

// Create the blocking pool
let blocking_pool =
Expand Down Expand Up @@ -1295,7 +1296,7 @@ cfg_rt_multi_thread! {
use crate::runtime::scheduler::MultiThreadAlt;

let core_threads = self.worker_threads.unwrap_or_else(num_cpus);
let (driver, driver_handle) = driver::Driver::new(self.get_cfg())?;
let (driver, driver_handle) = driver::Driver::new(self.get_cfg(core_threads))?;

// Create the blocking pool
let blocking_pool =
Expand Down
12 changes: 8 additions & 4 deletions tokio/src/runtime/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use crate::runtime::coop;

use std::cell::Cell;

#[cfg(any(feature = "rt", feature = "macros"))]
#[cfg(any(feature = "rt", feature = "macros", feature = "time"))]
use crate::util::rand::FastRand;

cfg_rt! {
Expand Down Expand Up @@ -57,7 +57,7 @@ struct Context {
#[cfg(feature = "rt")]
runtime: Cell<EnterRuntime>,

#[cfg(any(feature = "rt", feature = "macros"))]
#[cfg(any(feature = "rt", feature = "macros", feature = "time"))]
rng: Cell<Option<FastRand>>,

/// Tracks the amount of "work" a task may still do before yielding back to
Expand Down Expand Up @@ -100,7 +100,7 @@ tokio_thread_local! {
#[cfg(feature = "rt")]
runtime: Cell::new(EnterRuntime::NotEntered),

#[cfg(any(feature = "rt", feature = "macros"))]
#[cfg(any(feature = "rt", feature = "macros", feature = "time"))]
rng: Cell::new(None),

budget: Cell::new(coop::Budget::unconstrained()),
Expand All @@ -121,7 +121,11 @@ tokio_thread_local! {
}
}

#[cfg(any(feature = "macros", all(feature = "sync", feature = "rt")))]
#[cfg(any(
feature = "time",
feature = "macros",
all(feature = "sync", feature = "rt")
))]
pub(crate) fn thread_rng_n(n: u32) -> u32 {
CONTEXT.with(|ctx| {
let mut rng = ctx.rng.get().unwrap_or_else(FastRand::new);
Expand Down
8 changes: 6 additions & 2 deletions tokio/src/runtime/driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ pub(crate) struct Cfg {
pub(crate) enable_pause_time: bool,
pub(crate) start_paused: bool,
pub(crate) nevents: usize,
pub(crate) workers: usize,
}

impl Driver {
Expand All @@ -48,7 +49,8 @@ impl Driver {

let clock = create_clock(cfg.enable_pause_time, cfg.start_paused);

let (time_driver, time_handle) = create_time_driver(cfg.enable_time, io_stack, &clock);
let (time_driver, time_handle) =
create_time_driver(cfg.enable_time, io_stack, &clock, cfg.workers);

Ok((
Self { inner: time_driver },
Expand Down Expand Up @@ -306,9 +308,10 @@ cfg_time! {
enable: bool,
io_stack: IoStack,
clock: &Clock,
workers: usize,
) -> (TimeDriver, TimeHandle) {
if enable {
let (driver, handle) = crate::runtime::time::Driver::new(io_stack, clock);
let (driver, handle) = crate::runtime::time::Driver::new(io_stack, clock, workers as u32);

(TimeDriver::Enabled { driver }, Some(handle))
} else {
Expand Down Expand Up @@ -361,6 +364,7 @@ cfg_not_time! {
_enable: bool,
io_stack: IoStack,
_clock: &Clock,
_workers: usize,
) -> (TimeDriver, TimeHandle) {
(io_stack, ())
}
Expand Down
5 changes: 5 additions & 0 deletions tokio/src/runtime/scheduler/multi_thread/worker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -742,6 +742,11 @@ impl Context {
pub(crate) fn defer(&self, waker: &Waker) {
self.defer.defer(waker);
}

#[allow(dead_code)]
pub(crate) fn get_worker_index(&self) -> usize {
self.worker.index
}
}

impl Core {
Expand Down
5 changes: 5 additions & 0 deletions tokio/src/runtime/scheduler/multi_thread_alt/worker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1311,6 +1311,11 @@ impl Context {
fn shared(&self) -> &Shared {
&self.handle.shared
}

#[allow(dead_code)]
Darksonn marked this conversation as resolved.
Show resolved Hide resolved
pub(crate) fn get_worker_index(&self) -> usize {
self.index
}
}

impl Core {
Expand Down
39 changes: 37 additions & 2 deletions tokio/src/runtime/time/entry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ use crate::loom::cell::UnsafeCell;
use crate::loom::sync::atomic::AtomicU64;
use crate::loom::sync::atomic::Ordering;

use crate::runtime::context;
use crate::runtime::scheduler;
use crate::sync::AtomicWaker;
use crate::time::Instant;
Expand Down Expand Up @@ -328,6 +329,8 @@ pub(super) type EntryList = crate::util::linked_list::LinkedList<TimerShared, Ti
///
/// Note that this structure is located inside the `TimerEntry` structure.
pub(crate) struct TimerShared {
/// The shard id. We should never change it.
shard_id: u32,
/// A link within the doubly-linked list of timers on a particular level and
/// slot. Valid only if state is equal to Registered.
///
Expand Down Expand Up @@ -368,8 +371,9 @@ generate_addr_of_methods! {
}

impl TimerShared {
pub(super) fn new() -> Self {
pub(super) fn new(shard_id: u32) -> Self {
Self {
shard_id,
cached_when: AtomicU64::new(0),
pointers: linked_list::Pointers::new(),
state: StateCell::default(),
Expand Down Expand Up @@ -438,6 +442,11 @@ impl TimerShared {
pub(super) fn might_be_registered(&self) -> bool {
self.state.might_be_registered()
}

/// Gets the shard id.
pub(super) fn shard_id(&self) -> u32 {
self.shard_id
}
}

unsafe impl linked_list::Link for TimerShared {
Expand Down Expand Up @@ -485,13 +494,39 @@ impl TimerEntry {
fn inner(&self) -> &TimerShared {
let inner = unsafe { &*self.inner.get() };
if inner.is_none() {
let shard_id = self.get_shard_id();
unsafe {
*self.inner.get() = Some(TimerShared::new());
*self.inner.get() = Some(TimerShared::new(shard_id));
}
}
return inner.as_ref().unwrap();
}

// Gets the shard id. If current thread is a worker thread, we use its worker index as a shard id.
// Otherwise, we use a random number generator to obtain the shard id.
cfg_rt! {
fn get_shard_id(&self) -> u32 {
let shard_size = self.driver.driver().time().inner.get_shard_size();
let id = context::with_scheduler(|ctx| match ctx {
Some(scheduler::Context::CurrentThread(_ctx)) => 0,
#[cfg(feature = "rt-multi-thread")]
Some(scheduler::Context::MultiThread(ctx)) => ctx.get_worker_index() as u32,
#[cfg(all(tokio_unstable, feature = "rt-multi-thread"))]
Some(scheduler::Context::MultiThreadAlt(ctx)) => ctx.get_worker_index() as u32,
_ => context::thread_rng_n(shard_size),
});
id % shard_size
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

This sounds like a getter for a value that is already created, but actually it is the logic for figuring out which shard to use for a new timer. Can we rename this, and perhaps move it to a stand-alone function instead of a method on TimerEntry. Otherwise I am worried that someone will call it and expect it to return the same value as what the TimerShared is using.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Thanks for this CR. I would like to make it not a method of TimerEntry, and rename it to generate_shard_id.


cfg_not_rt! {
fn get_shard_id(&self) -> u32 {
let shard_size = self.driver.driver().time().inner.get_shard_size();
let id = context::thread_rng_n(shard_size);
id % shard_size
}
}

pub(crate) fn deadline(&self) -> Instant {
self.deadline
}
Expand Down
Loading
Loading