@@ -827,22 +827,33 @@ const NOTIFIED: usize = 2;
827827///
828828/// ```
829829/// use std::thread;
830+ /// use std::sync::{Arc, atomic::{Ordering, AtomicBool}};
830831/// use std::time::Duration;
831832///
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) {
834840/// println!("Parking thread");
835841/// thread::park();
836842/// // 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.
837844/// println!("Thread unparked");
838- /// })
839- /// .unwrap();
845+ /// }
846+ /// println!("Flag received");
847+ /// });
840848///
841849/// // Let some time pass for the thread to be spawned.
842850/// thread::sleep(Duration::from_millis(10));
843851///
852+ /// // Set the flag, and let the thread wake up.
844853/// // There is no race condition here, if `unpark`
845854/// // happens first, `park` will return immediately.
855+ /// // Hence there is no risk of a deadlock.
856+ /// flag.store(true, Ordering::Release);
846857/// println!("Unpark the thread");
847858/// parked_thread.thread().unpark();
848859///
0 commit comments