Skip to content

Commit 2ae3595

Browse files
committed
Optimize accessing the foreign registry by referencing either it or the global reference in the TLS variable
1 parent dc5286c commit 2ae3595

File tree

1 file changed

+29
-13
lines changed

1 file changed

+29
-13
lines changed

rayon-core/src/registry.rs

Lines changed: 29 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -217,9 +217,28 @@ fn default_global_registry() -> Result<Arc<Registry>, ThreadPoolBuildError> {
217217
result
218218
}
219219

220-
// A registry which is used only temporarily and is not associated to a worker thread.
220+
// A pointer to the global registry if it was initialized or a temporary reference if the current thread is not a worker thread.
221221
thread_local! {
222-
static FOREIGN_REGISTRY: Cell<*const Arc<Registry>> = const { Cell::new(ptr::null()) };
222+
static CURRENT_REGISTRY: Cell<*const Arc<Registry>> = const { Cell::new(ptr::null()) };
223+
}
224+
225+
#[cold]
226+
fn set_current_registry_to_global_registry() -> *const Arc<Registry> {
227+
let global = global_registry();
228+
229+
CURRENT_REGISTRY.with(|current_registry| current_registry.set(global));
230+
231+
global
232+
}
233+
234+
unsafe fn current_registry<'a>() -> &'a Arc<Registry> {
235+
let mut current = CURRENT_REGISTRY.with(Cell::get);
236+
237+
if current.is_null() {
238+
current = set_current_registry_to_global_registry();
239+
}
240+
241+
&*current
223242
}
224243

225244
struct Terminator<'a>(&'a Arc<Registry>);
@@ -320,13 +339,7 @@ impl Registry {
320339
unsafe {
321340
let worker_thread = WorkerThread::current();
322341
let registry = if worker_thread.is_null() {
323-
let foreign_registry = FOREIGN_REGISTRY.with(Cell::get);
324-
325-
if foreign_registry.is_null() {
326-
global_registry()
327-
} else {
328-
&*foreign_registry
329-
}
342+
current_registry()
330343
} else {
331344
&(*worker_thread).registry
332345
};
@@ -338,19 +351,22 @@ impl Registry {
338351
where
339352
F: FnOnce() -> R,
340353
{
341-
struct Guard;
354+
struct Guard {
355+
current: *const Arc<Registry>,
356+
}
342357

343358
impl Guard {
344359
fn new(registry: &Arc<Registry>) -> Self {
345-
FOREIGN_REGISTRY.with(|foreign_registry| foreign_registry.set(registry));
360+
let current =
361+
CURRENT_REGISTRY.with(|current_registry| current_registry.replace(registry));
346362

347-
Self
363+
Self { current }
348364
}
349365
}
350366

351367
impl Drop for Guard {
352368
fn drop(&mut self) {
353-
FOREIGN_REGISTRY.with(|foreign_registry| foreign_registry.set(ptr::null()));
369+
CURRENT_REGISTRY.with(|current_registry| current_registry.set(self.current));
354370
}
355371
}
356372

0 commit comments

Comments
 (0)