Skip to content

Commit d9d26f0

Browse files
committed
Auto merge of #123433 - GnomedDev:remove-threadname-alloc, r=<try>
Remove rt::init allocation for thread name This removes one of the allocations in a `fn main() {}` program.
2 parents a4b11c8 + 0989416 commit d9d26f0

File tree

2 files changed

+27
-6
lines changed

2 files changed

+27
-6
lines changed

library/std/src/rt.rs

+1-3
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,6 @@
1616
#![deny(unsafe_op_in_unsafe_fn)]
1717
#![allow(unused_macros)]
1818

19-
use crate::ffi::CString;
20-
2119
// Re-export some of our utilities which are expected by other crates.
2220
pub use crate::panicking::{begin_panic, panic_count};
2321
pub use core::panicking::{panic_display, panic_fmt};
@@ -96,7 +94,7 @@ unsafe fn init(argc: isize, argv: *const *const u8, sigpipe: u8) {
9694
sys::init(argc, argv, sigpipe);
9795

9896
// Set up the current thread to give it the right name.
99-
let thread = Thread::new(Some(rtunwrap!(Ok, CString::new("main"))));
97+
let thread = Thread::new_main();
10098
thread::set_current(thread);
10199
}
102100
}

library/std/src/thread/mod.rs

+26-3
Original file line numberDiff line numberDiff line change
@@ -1247,9 +1247,16 @@ impl ThreadId {
12471247
// Thread
12481248
////////////////////////////////////////////////////////////////////////////////
12491249

1250+
/// The internal representation of a `Thread`'s name.
1251+
enum ThreadName {
1252+
Main,
1253+
Other(CString),
1254+
Unnamed,
1255+
}
1256+
12501257
/// The internal representation of a `Thread` handle
12511258
struct Inner {
1252-
name: Option<CString>, // Guaranteed to be UTF-8
1259+
name: ThreadName, // Guaranteed to be UTF-8
12531260
id: ThreadId,
12541261
parker: Parker,
12551262
}
@@ -1286,8 +1293,20 @@ pub struct Thread {
12861293

12871294
impl Thread {
12881295
// Used only internally to construct a thread object without spawning
1289-
// Panics if the name contains nuls.
12901296
pub(crate) fn new(name: Option<CString>) -> Thread {
1297+
if let Some(name) = name {
1298+
Self::new_inner(ThreadName::Other(name))
1299+
} else {
1300+
Self::new_inner(ThreadName::Unnamed)
1301+
}
1302+
}
1303+
1304+
// Used in runtime to construct main thread
1305+
pub(crate) fn new_main() -> Thread {
1306+
Self::new_inner(ThreadName::Main)
1307+
}
1308+
1309+
fn new_inner(name: ThreadName) -> Thread {
12911310
// We have to use `unsafe` here to construct the `Parker` in-place,
12921311
// which is required for the UNIX implementation.
12931312
//
@@ -1414,7 +1433,11 @@ impl Thread {
14141433
}
14151434

14161435
fn cname(&self) -> Option<&CStr> {
1417-
self.inner.name.as_deref()
1436+
match &self.inner.name {
1437+
ThreadName::Main => Some(c"main"),
1438+
ThreadName::Other(other) => Some(&other),
1439+
ThreadName::Unnamed => None,
1440+
}
14181441
}
14191442
}
14201443

0 commit comments

Comments
 (0)