@@ -217,9 +217,28 @@ fn default_global_registry() -> Result<Arc<Registry>, ThreadPoolBuildError> {
217
217
result
218
218
}
219
219
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.
221
221
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
223
242
}
224
243
225
244
struct Terminator < ' a > ( & ' a Arc < Registry > ) ;
@@ -320,13 +339,7 @@ impl Registry {
320
339
unsafe {
321
340
let worker_thread = WorkerThread :: current ( ) ;
322
341
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 ( )
330
343
} else {
331
344
& ( * worker_thread) . registry
332
345
} ;
@@ -338,19 +351,22 @@ impl Registry {
338
351
where
339
352
F : FnOnce ( ) -> R ,
340
353
{
341
- struct Guard ;
354
+ struct Guard {
355
+ current : * const Arc < Registry > ,
356
+ }
342
357
343
358
impl Guard {
344
359
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) ) ;
346
362
347
- Self
363
+ Self { current }
348
364
}
349
365
}
350
366
351
367
impl Drop for Guard {
352
368
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 ) ) ;
354
370
}
355
371
}
356
372
0 commit comments