12 stable releases

2.2.1 Sep 7, 2024
2.2.0 Oct 18, 2023
2.1.1 Sep 25, 2023
2.1.0 Apr 7, 2023
1.0.1 May 28, 2020

#51 in Concurrency

Download history 828520/week @ 2024-08-20 802553/week @ 2024-08-27 889801/week @ 2024-09-03 895455/week @ 2024-09-10 858795/week @ 2024-09-17 951684/week @ 2024-09-24 943303/week @ 2024-10-01 969683/week @ 2024-10-08 1012589/week @ 2024-10-15 1051388/week @ 2024-10-22 1028924/week @ 2024-10-29 1038563/week @ 2024-11-05 1062328/week @ 2024-11-12 1072188/week @ 2024-11-19 912643/week @ 2024-11-26 887127/week @ 2024-12-03

4,100,930 downloads per month
Used in 5,625 crates (9 directly)

Apache-2.0 OR MIT

19KB
191 lines

parking

Build License Cargo Documentation

Thread parking and unparking.

A Parker is in either the notified or unnotified state. The park() method blocks the current thread until the Parker becomes notified and then puts it back into the unnotified state. The unpark() method puts it into the notified state.

This API is similar to thread::park() and Thread::unpark() from the standard library. The difference is that the state "token" managed by those functions is shared across an entire thread, and anyone can call thread::current() to access it. If you use park and unpark, but you also call a function that uses park and unpark internally, that function could cause a deadlock by consuming a wakeup that was intended for you. The Parker object in this crate avoids that problem by managing its own state, which isn't shared with unrelated callers.

Examples

use std::thread;
use std::time::Duration;
use parking::Parker;

let p = Parker::new();
let u = p.unparker();

// Notify the parker.
u.unpark();

// Wakes up immediately because the parker is notified.
p.park();

thread::spawn(move || {
    thread::sleep(Duration::from_millis(500));
    u.unpark();
});

// Wakes up when `u.unpark()` notifies and then goes back into unnotified state.
p.park();

License

Licensed under either of

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.

Dependencies

~0–24MB
~333K SLoC