Skip to content

Commit c77b77a

Browse files
authored
chore: avoid redundant opendal runtime layer spawns (#20159)
fix(storage): avoid redundant IO runtime spawns
1 parent 0fd0d51 commit c77b77a

2 files changed

Lines changed: 269 additions & 48 deletions

File tree

src/common/base/src/runtime/runtime.rs

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ use futures::future;
2525
use log::warn;
2626
use tokio::runtime::Builder;
2727
use tokio::runtime::Handle;
28+
use tokio::runtime::Id;
2829
use tokio::sync::OwnedSemaphorePermit;
2930
use tokio::sync::Semaphore;
3031
use tokio::task::JoinHandle;
@@ -60,7 +61,7 @@ impl Runtime {
6061

6162
let handle = runtime.handle().clone();
6263
let runtime_name = name.clone().unwrap_or_else(|| "unnamed".to_string());
63-
let runtime_id = handle.id().to_string();
64+
let runtime_id = handle.id();
6465
let runtime_label = format!("{runtime_name} id={runtime_id}");
6566
let task_marker = format!("[{runtime_label}]");
6667

@@ -152,6 +153,12 @@ impl Runtime {
152153
self.handle.clone()
153154
}
154155

156+
/// Returns whether the caller is running in this runtime.
157+
#[inline]
158+
pub fn is_current(&self) -> bool {
159+
is_current_runtime(self.handle.id())
160+
}
161+
155162
fn task_location_name(&self, location_name: String) -> String {
156163
format!("{} {}", self.task_marker, location_name)
157164
}
@@ -298,7 +305,7 @@ impl Runtime {
298305
/// Dropping the dropper will cause runtime to shutdown.
299306
pub struct Dropper {
300307
name: Option<String>,
301-
runtime_id: String,
308+
runtime_id: Id,
302309
close: Option<std::sync::mpsc::Sender<WatchdogEvent>>,
303310
join_handler: Option<ThreadJoinHandle<bool>>,
304311
}
@@ -310,7 +317,7 @@ impl Drop for Dropper {
310317
if let Some(close_sender) = self.close.take()
311318
&& close_sender.send(WatchdogEvent::Stop).is_ok()
312319
{
313-
if self.is_dropping_from_own_runtime() {
320+
if is_current_runtime(self.runtime_id) {
314321
// The wait-to-drop thread owns the Tokio runtime and will shut it down
315322
// after observing the stop signal. Joining it from one of the same
316323
// runtime's workers would deadlock: shutdown waits for this worker to
@@ -337,12 +344,11 @@ impl Drop for Dropper {
337344
}
338345
}
339346

340-
impl Dropper {
341-
fn is_dropping_from_own_runtime(&self) -> bool {
342-
match Handle::try_current() {
343-
Ok(handle) => handle.id().to_string() == self.runtime_id,
344-
Err(_) => false,
345-
}
347+
#[inline]
348+
fn is_current_runtime(runtime_id: Id) -> bool {
349+
match Handle::try_current() {
350+
Ok(handle) => handle.id() == runtime_id,
351+
Err(_) => false,
346352
}
347353
}
348354

0 commit comments

Comments
 (0)