Skip to content

Commit 30840c5

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

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
@@ -1245,9 +1245,16 @@ impl ThreadId {
12451245
// Thread
12461246
////////////////////////////////////////////////////////////////////////////////
12471247

1248+
/// The internal representation of a `Thread`'s name.
1249+
enum ThreadName {
1250+
Main,
1251+
Other(CString),
1252+
Unnamed,
1253+
}
1254+
12481255
/// The internal representation of a `Thread` handle
12491256
struct Inner {
1250-
name: Option<CString>, // Guaranteed to be UTF-8
1257+
name: ThreadName, // Guaranteed to be UTF-8
12511258
id: ThreadId,
12521259
parker: Parker,
12531260
}
@@ -1284,8 +1291,20 @@ pub struct Thread {
12841291

12851292
impl Thread {
12861293
// Used only internally to construct a thread object without spawning
1287-
// Panics if the name contains nuls.
12881294
pub(crate) fn new(name: Option<CString>) -> Thread {
1295+
if let Some(name) = name {
1296+
Self::new_inner(ThreadName::Other(name))
1297+
} else {
1298+
Self::new_inner(ThreadName::Unnamed)
1299+
}
1300+
}
1301+
1302+
// Used in runtime to construct main thread
1303+
pub(crate) fn new_main() -> Thread {
1304+
Self::new_inner(ThreadName::Main)
1305+
}
1306+
1307+
fn new_inner(name: ThreadName) -> Thread {
12891308
// We have to use `unsafe` here to construct the `Parker` in-place,
12901309
// which is required for the UNIX implementation.
12911310
//
@@ -1412,7 +1431,11 @@ impl Thread {
14121431
}
14131432

14141433
fn cname(&self) -> Option<&CStr> {
1415-
self.inner.name.as_deref()
1434+
match &self.inner.name {
1435+
ThreadName::Main => Some(c"main"),
1436+
ThreadName::Other(other) => Some(&other),
1437+
ThreadName::Unnamed => None,
1438+
}
14161439
}
14171440
}
14181441

0 commit comments

Comments
 (0)