Skip to content

Commit d2a958f

Browse files
authored
Rollup merge of rust-lang#59291 - SimonSapin:nonzero-thread-id, r=alexcrichton
Make Option<ThreadId> no larger than ThreadId, with NonZeroU64
2 parents 28644cd + c1d9191 commit d2a958f

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

src/libstd/thread/mod.rs

+11-4
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,7 @@ use crate::ffi::{CStr, CString};
163163
use crate::fmt;
164164
use crate::io;
165165
use crate::mem;
166+
use crate::num::NonZeroU64;
166167
use crate::panic;
167168
use crate::panicking;
168169
use crate::str;
@@ -1036,15 +1037,15 @@ pub fn park_timeout(dur: Duration) {
10361037
/// [`Thread`]: ../../std/thread/struct.Thread.html
10371038
#[stable(feature = "thread_id", since = "1.19.0")]
10381039
#[derive(Eq, PartialEq, Clone, Copy, Hash, Debug)]
1039-
pub struct ThreadId(u64);
1040+
pub struct ThreadId(NonZeroU64);
10401041

10411042
impl ThreadId {
10421043
// Generate a new unique thread ID.
10431044
fn new() -> ThreadId {
10441045
// We never call `GUARD.init()`, so it is UB to attempt to
10451046
// acquire this mutex reentrantly!
10461047
static GUARD: mutex::Mutex = mutex::Mutex::new();
1047-
static mut COUNTER: u64 = 0;
1048+
static mut COUNTER: u64 = 1;
10481049

10491050
unsafe {
10501051
let _guard = GUARD.lock();
@@ -1058,7 +1059,7 @@ impl ThreadId {
10581059
let id = COUNTER;
10591060
COUNTER += 1;
10601061

1061-
ThreadId(id)
1062+
ThreadId(NonZeroU64::new(id).unwrap())
10621063
}
10631064
}
10641065
}
@@ -1484,9 +1485,10 @@ fn _assert_sync_and_send() {
14841485
mod tests {
14851486
use super::Builder;
14861487
use crate::any::Any;
1488+
use crate::mem;
14871489
use crate::sync::mpsc::{channel, Sender};
14881490
use crate::result;
1489-
use crate::thread;
1491+
use crate::thread::{self, ThreadId};
14901492
use crate::time::Duration;
14911493
use crate::u32;
14921494

@@ -1716,6 +1718,11 @@ mod tests {
17161718
thread::sleep(Duration::from_millis(2));
17171719
}
17181720

1721+
#[test]
1722+
fn test_size_of_option_thread_id() {
1723+
assert_eq!(mem::size_of::<Option<ThreadId>>(), mem::size_of::<ThreadId>());
1724+
}
1725+
17191726
#[test]
17201727
fn test_thread_id_equal() {
17211728
assert!(thread::current().id() == thread::current().id());

0 commit comments

Comments
 (0)