Skip to content

Commit

Permalink
Thread stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
terrarier2111 committed Jul 20, 2023
1 parent a121f5f commit b5221a2
Showing 1 changed file with 9 additions and 7 deletions.
16 changes: 9 additions & 7 deletions src/thread_id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use std::collections::BinaryHeap;
use std::{mem, ptr};
use std::mem::MaybeUninit;
use std::num::NonZeroUsize;
use std::ptr::addr_of;
use std::ptr::{addr_of, null};

/// Thread ID manager which allocates thread IDs. It attempts to aggressively
/// reuse thread IDs where possible to avoid cases where a ThreadLocal grows
Expand Down Expand Up @@ -52,20 +52,22 @@ static THREAD_ID_MANAGER: Lazy<Mutex<ThreadIdManager>> =
/// Data which is unique to the current thread while it is running.
/// A thread ID may be reused after a thread exits.
#[derive(Clone, Copy)]
#[repr(C)]
pub(crate) struct Thread {
init: bool,
self_ptr: *const Thread,
id: usize,
bucket: usize,
index: usize,
}

impl Thread {
#[inline]
fn new(id: usize) -> Self {
let bucket = usize::from(POINTER_WIDTH) - ((id - 1).leading_zeros() as usize) - 1;
let bucket_size = 1 << bucket;
let index = id - (bucket_size - 1);
Self {
init: true,
self_ptr: THREAD.get().cast_const(),
id,
bucket,
index,
Expand Down Expand Up @@ -108,7 +110,7 @@ cfg_if::cfg_if! {
// This makes the fast path smaller.
#[thread_local]
static THREAD: UnsafeCell<Thread> = UnsafeCell::new(Thread {
init: false,
self_ptr: null(),
id: 0,
index: 0,
bucket: 0,
Expand All @@ -129,7 +131,7 @@ cfg_if::cfg_if! {
// will go through get_slow which will either panic or
// initialize a new ThreadGuard.
unsafe {
(&mut *THREAD.get()).init = false;
(&mut *THREAD.get()).self_ptr = null();
}
THREAD_ID_MANAGER.lock().free(self.id.get());
}
Expand All @@ -141,8 +143,8 @@ cfg_if::cfg_if! {
use std::intrinsics::likely;
// prefetch_read_data();
let thread = unsafe { *THREAD.get() };
if likely(thread.init) {
thread
if likely(!thread.self_ptr.is_null()) {
unsafe { thread.self_ptr.read() }
} else {
get_slow()
}
Expand Down

0 comments on commit b5221a2

Please sign in to comment.