Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion library/std/src/thread/current.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ pub(super) mod id {
get().unwrap_or_else(
#[cold]
|| {
let id = ThreadId::new();
let id = ThreadId::desperate_new();
id::set(id);
id
},
Expand Down
29 changes: 26 additions & 3 deletions library/std/src/thread/id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,15 @@ use crate::sync::atomic::{Atomic, Ordering};
pub struct ThreadId(NonZero<u64>);

impl ThreadId {
// Generate a new unique thread ID.
pub(crate) fn new() -> ThreadId {
/// Generates a new unique thread ID, and does not rely on the global
/// allocator.
///
/// This should only be used in contexts where a new `ThreadId` is
/// desperately required, but the global allocator might not be available.
pub(super) fn desperate_new() -> ThreadId {
#[cold]
fn exhausted() -> ! {
panic!("failed to generate unique thread ID: bitspace exhausted")
rtabort!("failed to generate unique thread ID: bitspace exhausted")
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Panicking may allocate, so it shouldn't be used here either.

}

cfg_select! {
Expand Down Expand Up @@ -96,6 +100,25 @@ impl ThreadId {
}
}

/// Generates a new unique thread ID.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
/// Generates a new unique thread ID.
/// Generates a new unique thread ID. Might use the global allocator.

pub(crate) fn new() -> ThreadId {
cfg_select! {
target_has_atomic = "64" => {
// The generation is implemented lock-free anyway.
ThreadId::desperate_new()
}
_ => {
// Synchronize the id generation – `Mutex` has better
// synchronization behaviour than the spinlock used in
// `desperate_new`, but might need allocation.
use crate::sync::nonpoison::Mutex;
static LOCK: Mutex<()> = Mutex::new(());
let _guard = LOCK.lock();
ThreadId::desperate_new()
}
}
}

#[cfg(any(not(target_thread_local), target_has_atomic = "64"))]
pub(super) fn from_u64(v: u64) -> Option<ThreadId> {
NonZero::new(v).map(ThreadId)
Expand Down
Loading