Skip to content

Commit

Permalink
Rollup merge of rust-lang#59291 - SimonSapin:nonzero-thread-id, r=ale…
Browse files Browse the repository at this point in the history
…xcrichton

Make Option<ThreadId> no larger than ThreadId, with NonZeroU64
  • Loading branch information
Centril authored Mar 22, 2019
2 parents 28644cd + c1d9191 commit d2a958f
Showing 1 changed file with 11 additions and 4 deletions.
15 changes: 11 additions & 4 deletions src/libstd/thread/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ use crate::ffi::{CStr, CString};
use crate::fmt;
use crate::io;
use crate::mem;
use crate::num::NonZeroU64;
use crate::panic;
use crate::panicking;
use crate::str;
Expand Down Expand Up @@ -1036,15 +1037,15 @@ pub fn park_timeout(dur: Duration) {
/// [`Thread`]: ../../std/thread/struct.Thread.html
#[stable(feature = "thread_id", since = "1.19.0")]
#[derive(Eq, PartialEq, Clone, Copy, Hash, Debug)]
pub struct ThreadId(u64);
pub struct ThreadId(NonZeroU64);

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

unsafe {
let _guard = GUARD.lock();
Expand All @@ -1058,7 +1059,7 @@ impl ThreadId {
let id = COUNTER;
COUNTER += 1;

ThreadId(id)
ThreadId(NonZeroU64::new(id).unwrap())
}
}
}
Expand Down Expand Up @@ -1484,9 +1485,10 @@ fn _assert_sync_and_send() {
mod tests {
use super::Builder;
use crate::any::Any;
use crate::mem;
use crate::sync::mpsc::{channel, Sender};
use crate::result;
use crate::thread;
use crate::thread::{self, ThreadId};
use crate::time::Duration;
use crate::u32;

Expand Down Expand Up @@ -1716,6 +1718,11 @@ mod tests {
thread::sleep(Duration::from_millis(2));
}

#[test]
fn test_size_of_option_thread_id() {
assert_eq!(mem::size_of::<Option<ThreadId>>(), mem::size_of::<ThreadId>());
}

#[test]
fn test_thread_id_equal() {
assert!(thread::current().id() == thread::current().id());
Expand Down

0 comments on commit d2a958f

Please sign in to comment.