Rollup merge of #132730 - joboet:after_main_sync, r=Noratrieb
std: allow after-main use of synchronization primitives By creating an unnamed thread handle when the actual one has already been destroyed, synchronization primitives using thread parking can be used even outside the Rust runtime. This also fixes an inefficiency in the queue-based `RwLock`: if `thread::current` was not initialized yet, it will create a new handle on every parking attempt without initializing `thread::current`. The private `current_or_unnamed` function introduced here fixes this.
This commit is contained in:
@@ -93,7 +93,7 @@ const QUEUE_MASK: usize = !STATE_MASK;
|
||||
// use interior mutability.
|
||||
#[repr(align(4))] // Ensure the two lower bits are free to use as state bits.
|
||||
struct Waiter {
|
||||
thread: Cell<Option<Thread>>,
|
||||
thread: Thread,
|
||||
signaled: AtomicBool,
|
||||
next: Cell<*const Waiter>,
|
||||
}
|
||||
@@ -238,7 +238,7 @@ fn wait(
|
||||
return_on_poisoned: bool,
|
||||
) -> StateAndQueue {
|
||||
let node = &Waiter {
|
||||
thread: Cell::new(Some(thread::current())),
|
||||
thread: thread::current_or_unnamed(),
|
||||
signaled: AtomicBool::new(false),
|
||||
next: Cell::new(ptr::null()),
|
||||
};
|
||||
@@ -277,7 +277,8 @@ fn wait(
|
||||
// can park ourselves, the result could be this thread never gets
|
||||
// unparked. Luckily `park` comes with the guarantee that if it got
|
||||
// an `unpark` just before on an unparked thread it does not park.
|
||||
thread::park();
|
||||
// SAFETY: we retrieved this handle on the current thread above.
|
||||
unsafe { node.thread.park() }
|
||||
}
|
||||
|
||||
return state_and_queue.load(Acquire);
|
||||
@@ -309,7 +310,7 @@ impl Drop for WaiterQueue<'_> {
|
||||
let mut queue = to_queue(current);
|
||||
while !queue.is_null() {
|
||||
let next = (*queue).next.get();
|
||||
let thread = (*queue).thread.take().unwrap();
|
||||
let thread = (*queue).thread.clone();
|
||||
(*queue).signaled.store(true, Release);
|
||||
thread.unpark();
|
||||
queue = next;
|
||||
|
||||
@@ -118,7 +118,7 @@ use crate::mem;
|
||||
use crate::ptr::{self, NonNull, null_mut, without_provenance_mut};
|
||||
use crate::sync::atomic::Ordering::{AcqRel, Acquire, Relaxed, Release};
|
||||
use crate::sync::atomic::{AtomicBool, AtomicPtr};
|
||||
use crate::thread::{self, Thread, ThreadId};
|
||||
use crate::thread::{self, Thread};
|
||||
|
||||
/// The atomic lock state.
|
||||
type AtomicState = AtomicPtr<()>;
|
||||
@@ -217,9 +217,7 @@ impl Node {
|
||||
/// Prepare this node for waiting.
|
||||
fn prepare(&mut self) {
|
||||
// Fall back to creating an unnamed `Thread` handle to allow locking in TLS destructors.
|
||||
self.thread.get_or_init(|| {
|
||||
thread::try_current().unwrap_or_else(|| Thread::new_unnamed(ThreadId::new()))
|
||||
});
|
||||
self.thread.get_or_init(thread::current_or_unnamed);
|
||||
self.completed = AtomicBool::new(false);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user