Skip to content

Commit

Permalink
Use NonZeroUsize in GetThreadId::nonzero_thread_id
Browse files Browse the repository at this point in the history
  • Loading branch information
faern committed Jun 3, 2019
1 parent 45f5483 commit 0a5dd34
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 12 deletions.
25 changes: 15 additions & 10 deletions lock_api/src/remutex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,19 @@
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.

use crate::mutex::{RawMutex, RawMutexFair, RawMutexTimed};
use crate::GuardNoSend;
use core::cell::{Cell, UnsafeCell};
use core::fmt;
use core::marker::PhantomData;
use core::mem;
use core::ops::Deref;
use core::sync::atomic::{AtomicUsize, Ordering};
use crate::{
mutex::{RawMutex, RawMutexFair, RawMutexTimed},
GuardNoSend,
};
use core::{
cell::{Cell, UnsafeCell},
fmt,
marker::PhantomData,
mem,
num::NonZeroUsize,
ops::Deref,
sync::atomic::{AtomicUsize, Ordering},
};

#[cfg(feature = "owning_ref")]
use owning_ref::StableAddress;
Expand All @@ -36,7 +41,7 @@ pub unsafe trait GetThreadId {

/// Returns a non-zero thread ID which identifies the current thread of
/// execution.
fn nonzero_thread_id(&self) -> usize;
fn nonzero_thread_id(&self) -> NonZeroUsize;
}

struct RawReentrantMutex<R: RawMutex, G: GetThreadId> {
Expand All @@ -49,7 +54,7 @@ struct RawReentrantMutex<R: RawMutex, G: GetThreadId> {
impl<R: RawMutex, G: GetThreadId> RawReentrantMutex<R, G> {
#[inline]
fn lock_internal<F: FnOnce() -> bool>(&self, try_lock: F) -> bool {
let id = self.get_thread_id.nonzero_thread_id();
let id = self.get_thread_id.nonzero_thread_id().get();
if self.owner.load(Ordering::Relaxed) == id {
self.lock_count.set(
self.lock_count.get().checked_add(1).expect("ReentrantMutex lock count overflow"),
Expand Down
8 changes: 6 additions & 2 deletions src/remutex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
// copied, modified, or distributed except according to those terms.

use crate::raw_mutex::RawMutex;
use core::num::NonZeroUsize;
use lock_api::{self, GetThreadId};

/// Implementation of the `GetThreadId` trait for `lock_api::ReentrantMutex`.
Expand All @@ -14,11 +15,14 @@ pub struct RawThreadId;
unsafe impl GetThreadId for RawThreadId {
const INIT: RawThreadId = RawThreadId;

fn nonzero_thread_id(&self) -> usize {
fn nonzero_thread_id(&self) -> NonZeroUsize {
// The address of a thread-local variable is guaranteed to be unique to the
// current thread, and is also guaranteed to be non-zero.
thread_local!(static KEY: u8 = unsafe { ::std::mem::uninitialized() });
KEY.with(|x| x as *const _ as usize)
KEY.with(|x| {
NonZeroUsize::new(x as *const _ as usize)
.expect("thread-local variable address is null")
})
}
}

Expand Down

0 comments on commit 0a5dd34

Please sign in to comment.