parking
Thread parking and unparking.
This is a copy of the
park()/unpark() mechanism from
the standard library.
What is parking
Conceptually, each Parker has a token which is initially not present:
-
The
Parker::park()method blocks the current thread unless or until the token is available, at which point it automatically consumes the token. It may also return spuriously, without consuming the token. -
The
Parker::park_timeout()method works the same asParker::park(), but blocks until a timeout is reached. -
The
Parker::park_deadline()method works the same asParker::park(), but blocks until a deadline is reached. -
The
Parker::unpark()andUnparker::unpark()methods atomically make the token available if it wasn't already. Because the token is initially absent,Unparker::unpark()followed byParker::park()will result in the second call returning immediately.
Analogy with channels
Another way of thinking about Parker is as a bounded
channel with capacity of 1.
Then, Parker::park() is equivalent to blocking on a
receive operation, and Unparker::unpark() is
equivalent to a non-blocking send operation.
Examples
use thread;
use Duration;
use Parker;
let p = new;
let u = p.unparker;
// Make the token available.
u.unpark;
// Wakes up immediately and consumes the token.
p.park;
spawn;
// Wakes up when `u.unpark()` provides the token, but may also wake up
// spuriously before that without consuming the token.
p.park;
License
Licensed under either of
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.
Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.