pub fn park()
Expand description
Blocks unless or until the current thread’s token is made available.
A call to park
does not guarantee that the thread will remain parked
forever, and callers should be prepared for this possibility. However,
it is guaranteed that this function will not panic (it may abort the
process if the implementation encounters some rare errors).
§park
and unpark
Every thread is equipped with some basic low-level blocking support, via the
thread::park
function and thread::Thread::unpark
method. park
blocks the current thread, which can then be resumed from
another thread by calling the unpark
method on the blocked thread’s
handle.
Conceptually, each Thread
handle has an associated token, which is
initially not present:
-
The
thread::park
function blocks the current thread unless or until the token is available for its thread handle, at which point it atomically consumes the token. It may also return spuriously, without consuming the token.thread::park_timeout
does the same, but allows specifying a maximum time to block the thread for. -
The
unpark
method on aThread
atomically makes the token available if it wasn’t already. Because the token can be held by a thread even if it is currently not parked,unpark
followed bypark
will result in the second call returning immediately. However, note that to rely on this guarantee, you need to make sure that yourunpark
happens after allpark
that may be done by other data structures!
The API is typically used by acquiring a handle to the current thread, placing that handle in a
shared data structure so that other threads can find it, and then park
ing in a loop. When some
desired condition is met, another thread calls unpark
on the handle. The last bullet point
above guarantees that even if the unpark
occurs before the thread is finished park
ing, it
will be woken up properly.
Note that the coordination via the shared data structure is crucial: If you unpark
a thread
without first establishing that it is about to be park
ing within your code, that unpark
may
get consumed by a different park
in the same thread, leading to a deadlock. This also means
you must not call unknown code between setting up for parking and calling park
; for instance,
if you invoke println!
, that may itself call park
and thus consume your unpark
and cause a
deadlock.
The motivation for this design is twofold:
-
It avoids the need to allocate mutexes and condvars when building new synchronization primitives; the threads already provide basic blocking/signaling.
-
It can be implemented very efficiently on many platforms.
§Memory Ordering
Calls to unpark
synchronize-with calls to park
, meaning that memory
operations performed before a call to unpark
are made visible to the thread that
consumes the token and returns from park
. Note that all park
and unpark
operations for a given thread form a total order and all prior unpark
operations
synchronize-with park
.
In atomic ordering terms, unpark
performs a Release
operation and park
performs the corresponding Acquire
operation. Calls to unpark
for the same
thread form a release sequence.
Note that being unblocked does not imply a call was made to unpark
, because
wakeups can also be spurious. For example, a valid, but inefficient,
implementation could have park
and unpark
return immediately without doing anything,
making all wakeups spurious.
§Examples
use std::thread;
use std::sync::atomic::{Ordering, AtomicBool};
use std::time::Duration;
static QUEUED: AtomicBool = AtomicBool::new(false);
static FLAG: AtomicBool = AtomicBool::new(false);
let parked_thread = thread::spawn(move || {
println!("Thread spawned");
// Signal that we are going to `park`. Between this store and our `park`, there may
// be no other `park`, or else that `park` could consume our `unpark` token!
QUEUED.store(true, Ordering::Release);
// We want to wait until the flag is set. We *could* just spin, but using
// park/unpark is more efficient.
while !FLAG.load(Ordering::Acquire) {
// We can *not* use `println!` here since that could use thread parking internally.
thread::park();
// We *could* get here spuriously, i.e., way before the 10ms below are over!
// But that is no problem, we are in a loop until the flag is set anyway.
}
println!("Flag received");
});
// Let some time pass for the thread to be spawned.
thread::sleep(Duration::from_millis(10));
// Ensure the thread is about to park.
// This is crucial! It guarantees that the `unpark` below is not consumed
// by some other code in the parked thread (e.g. inside `println!`).
while !QUEUED.load(Ordering::Acquire) {
// Spinning is of course inefficient; in practice, this would more likely be
// a dequeue where we have no work to do if there's nobody queued.
std::hint::spin_loop();
}
// Set the flag, and let the thread wake up.
// There is no race condition here: if `unpark`
// happens first, `park` will return immediately.
// There is also no other `park` that could consume this token,
// since we waited until the other thread got queued.
// Hence there is no risk of a deadlock.
FLAG.store(true, Ordering::Release);
println!("Unpark the thread");
parked_thread.thread().unpark();
parked_thread.join().unwrap();