@@ -10,16 +10,42 @@ fn main() {
1010 . collect :: < String > ( ) ;
1111
1212 fn set_thread_name ( name : & CStr ) -> i32 {
13- #[ cfg( any( target_os = "linux" , target_os = "illumos" , target_os = "solaris" ) ) ]
14- return unsafe { libc:: pthread_setname_np ( libc:: pthread_self ( ) , name. as_ptr ( ) . cast ( ) ) } ;
15- #[ cfg( target_os = "freebsd" ) ]
16- unsafe {
17- // pthread_set_name_np does not return anything
18- libc:: pthread_set_name_np ( libc:: pthread_self ( ) , name. as_ptr ( ) . cast ( ) ) ;
19- return 0 ;
20- } ;
21- #[ cfg( target_os = "macos" ) ]
22- return unsafe { libc:: pthread_setname_np ( name. as_ptr ( ) . cast ( ) ) } ;
13+ cfg_if:: cfg_if! {
14+ if #[ cfg( any( target_os = "linux" , target_os = "illumos" , target_os = "solaris" ) ) ] {
15+ unsafe { libc:: pthread_setname_np( libc:: pthread_self( ) , name. as_ptr( ) . cast( ) ) }
16+ } else if #[ cfg( target_os = "freebsd" ) ] {
17+ // pthread_set_name_np does not return anything
18+ unsafe { libc:: pthread_set_name_np( libc:: pthread_self( ) , name. as_ptr( ) . cast( ) ) } ;
19+ 0
20+ } else if #[ cfg( target_os = "macos" ) ] {
21+ unsafe { libc:: pthread_setname_np( name. as_ptr( ) . cast( ) ) }
22+ } else {
23+ compile_error!( "set_thread_name not supported for this OS" )
24+ }
25+ }
26+ }
27+
28+ fn get_thread_name ( name : & mut [ u8 ] ) -> i32 {
29+ cfg_if:: cfg_if! {
30+ if #[ cfg( any(
31+ target_os = "linux" ,
32+ target_os = "illumos" ,
33+ target_os = "solaris" ,
34+ target_os = "macos"
35+ ) ) ] {
36+ unsafe {
37+ libc:: pthread_getname_np( libc:: pthread_self( ) , name. as_mut_ptr( ) . cast( ) , name. len( ) )
38+ }
39+ } else if #[ cfg( target_os = "freebsd" ) ] {
40+ // pthread_get_name_np does not return anything
41+ unsafe {
42+ libc:: pthread_get_name_np( libc:: pthread_self( ) , name. as_mut_ptr( ) . cast( ) , name. len( ) )
43+ } ;
44+ 0
45+ } else {
46+ compile_error!( "get_thread_name not supported for this OS" )
47+ }
48+ }
2349 }
2450
2551 let result = thread:: Builder :: new ( ) . name ( long_name. clone ( ) ) . spawn ( move || {
@@ -28,14 +54,7 @@ fn main() {
2854
2955 // But the system is limited -- make sure we successfully set a truncation.
3056 let mut buf = vec ! [ 0u8 ; long_name. len( ) + 1 ] ;
31- #[ cfg( not( target_os = "freebsd" ) ) ]
32- unsafe {
33- libc:: pthread_getname_np ( libc:: pthread_self ( ) , buf. as_mut_ptr ( ) . cast ( ) , buf. len ( ) )
34- } ;
35- #[ cfg( target_os = "freebsd" ) ]
36- unsafe {
37- libc:: pthread_get_name_np ( libc:: pthread_self ( ) , buf. as_mut_ptr ( ) . cast ( ) , buf. len ( ) )
38- } ;
57+ assert_eq ! ( get_thread_name( & mut buf) , 0 ) ;
3958 let cstr = CStr :: from_bytes_until_nul ( & buf) . unwrap ( ) ;
4059 assert ! ( cstr. to_bytes( ) . len( ) >= 15 , "name is too short: len={}" , cstr. to_bytes( ) . len( ) ) ; // POSIX seems to promise at least 15 chars
4160 assert ! ( long_name. as_bytes( ) . starts_with( cstr. to_bytes( ) ) ) ;
0 commit comments