1- use super :: { Thread , ThreadId , imp} ;
1+ use super :: id:: ThreadId ;
2+ use super :: main_thread;
3+ use super :: thread:: Thread ;
24use crate :: mem:: ManuallyDrop ;
35use crate :: ptr;
6+ use crate :: sys:: thread as imp;
47use crate :: sys:: thread_local:: local_pointer;
58
69const NONE : * mut ( ) = ptr:: null_mut ( ) ;
@@ -184,7 +187,7 @@ pub(crate) fn current_os_id() -> u64 {
184187
185188/// Gets a reference to the handle of the thread that invokes it, if the handle
186189/// has been initialized.
187- pub ( super ) fn try_with_current < F , R > ( f : F ) -> R
190+ fn try_with_current < F , R > ( f : F ) -> R
188191where
189192 F : FnOnce ( Option < & Thread > ) -> R ,
190193{
@@ -202,6 +205,36 @@ where
202205 }
203206}
204207
208+ /// Run a function with the current thread's name.
209+ ///
210+ /// Modulo thread local accesses, this function is safe to call from signal
211+ /// handlers and in similar circumstances where allocations are not possible.
212+ pub ( crate ) fn with_current_name < F , R > ( f : F ) -> R
213+ where
214+ F : FnOnce ( Option < & str > ) -> R ,
215+ {
216+ try_with_current ( |thread| {
217+ let name = if let Some ( thread) = thread {
218+ // If there is a current thread handle, try to use the name stored
219+ // there.
220+ thread. name ( )
221+ } else if let Some ( main) = main_thread:: get ( )
222+ && let Some ( id) = id:: get ( )
223+ && id == main
224+ {
225+ // The main thread doesn't always have a thread handle, we must
226+ // identify it through its ID instead. The checks are ordered so
227+ // that the current ID is only loaded if it is actually needed,
228+ // since loading it from TLS might need multiple expensive accesses.
229+ Some ( "main" )
230+ } else {
231+ None
232+ } ;
233+
234+ f ( name)
235+ } )
236+ }
237+
205238/// Gets a handle to the thread that invokes it. If the handle stored in thread-
206239/// local storage was already destroyed, this creates a new unnamed temporary
207240/// handle to allow thread parking in nearly all situations.
0 commit comments