pub fn park()
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.
Every thread is equipped with some basic low-level blocking support, via the
thread::park function and [
park blocks the current thread, which can then be resumed from
another thread by calling the [
unpark] method on the blocked thread's
Conceptually, each [
Thread] handle has an associated token, which is
initially not present:
thread::parkfunction 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.
unpark] method on a [
Thread] atomically makes the token available if it wasn't already. Because the token is initially absent, [
unpark] followed by
parkwill result in the second call returning immediately.
In other words, each [
Thread] acts a bit like a spinlock that can be
locked and unlocked using
Notice that being unblocked does not imply any synchronization with someone
that unparked this thread, it could also be spurious.
For example, it would be a valid, but inefficient, implementation to make both
unpark] return immediately without doing anything.
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
parking in a loop. When some desired condition is met, another
thread calls [
unpark] on the handle.
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.