@@ -827,22 +827,33 @@ const NOTIFIED: usize = 2;
827
827
///
828
828
/// ```
829
829
/// use std::thread;
830
+ /// use std::sync::{Arc, atomic::{Ordering, AtomicBool}};
830
831
/// use std::time::Duration;
831
832
///
832
- /// let parked_thread = thread::Builder::new()
833
- /// .spawn(|| {
833
+ /// let flag = Arc::new(AtomicBool::new(false));
834
+ /// let flag2 = Arc::clone(&flag);
835
+ ///
836
+ /// let parked_thread = thread::spawn(move || {
837
+ /// // We want to wait until the flag is set. We *could* just spin, but using
838
+ /// // park/unpark is more efficient.
839
+ /// while !flag2.load(Ordering::Acquire) {
834
840
/// println!("Parking thread");
835
841
/// thread::park();
836
842
/// // We *could* get here spuriously, i.e., way before the 10ms below are over!
843
+ /// // But that is no problem, we are in a loop until the flag is set anyway.
837
844
/// println!("Thread unparked");
838
- /// })
839
- /// .unwrap();
845
+ /// }
846
+ /// println!("Flag received");
847
+ /// });
840
848
///
841
849
/// // Let some time pass for the thread to be spawned.
842
850
/// thread::sleep(Duration::from_millis(10));
843
851
///
852
+ /// // Set the flag, and let the thread wake up.
844
853
/// // There is no race condition here, if `unpark`
845
854
/// // happens first, `park` will return immediately.
855
+ /// // Hence there is no risk of a deadlock.
856
+ /// flag.store(true, Ordering::Release);
846
857
/// println!("Unpark the thread");
847
858
/// parked_thread.thread().unpark();
848
859
///
0 commit comments