From af7eededaa2a239c1e23c40024cf557a4b83fffa Mon Sep 17 00:00:00 2001 From: bjorn3 Date: Thu, 16 Sep 2021 14:41:09 +0200 Subject: [PATCH] Remove an allocation from rt::init Previously the thread name would first be heap allocated and then re-allocated to add a nul terminator. Now it will be heap allocated only once with nul terminator added form the start. --- library/std/src/rt.rs | 4 +++- library/std/src/thread/mod.rs | 12 +++++------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/library/std/src/rt.rs b/library/std/src/rt.rs index 8e38f98105b1f..8465dfc0ab2fb 100644 --- a/library/std/src/rt.rs +++ b/library/std/src/rt.rs @@ -16,6 +16,8 @@ #![deny(unsafe_op_in_unsafe_fn)] #![allow(unused_macros)] +use crate::ffi::CString; + // Re-export some of our utilities which are expected by other crates. pub use crate::panicking::{begin_panic, begin_panic_fmt, panic_count}; @@ -38,7 +40,7 @@ unsafe fn init(argc: isize, argv: *const *const u8) { // created. Note that this isn't necessary in general for new threads, // but we just do this to name the main thread and to give it correct // info about the stack bounds. - let thread = Thread::new(Some("main".to_owned())); + let thread = Thread::new(Some(CString::new("main").unwrap())); thread_info::set(main_guard, thread); } } diff --git a/library/std/src/thread/mod.rs b/library/std/src/thread/mod.rs index f44df845bf4dd..9d659102b0320 100644 --- a/library/std/src/thread/mod.rs +++ b/library/std/src/thread/mod.rs @@ -457,7 +457,9 @@ impl Builder { let stack_size = stack_size.unwrap_or_else(thread::min_stack); - let my_thread = Thread::new(name); + let my_thread = Thread::new(name.map(|name| { + CString::new(name).expect("thread name may not contain interior null bytes") + })); let their_thread = my_thread.clone(); let my_packet: Arc>>> = Arc::new(UnsafeCell::new(None)); @@ -1073,12 +1075,8 @@ pub struct Thread { impl Thread { // Used only internally to construct a thread object without spawning // Panics if the name contains nuls. - pub(crate) fn new(name: Option) -> Thread { - let cname = - name.map(|n| CString::new(n).expect("thread name may not contain interior null bytes")); - Thread { - inner: Arc::new(Inner { name: cname, id: ThreadId::new(), parker: Parker::new() }), - } + pub(crate) fn new(name: Option) -> Thread { + Thread { inner: Arc::new(Inner { name, id: ThreadId::new(), parker: Parker::new() }) } } /// Atomically makes the handle's token available if it is not already.