about summary refs log tree commit diff
path: root/src/libstd/thread
diff options
context:
space:
mode:
authorRalf Jung <post@ralfj.de>2018-11-23 11:04:16 +0100
committerRalf Jung <post@ralfj.de>2018-11-23 11:04:16 +0100
commit7b6ad7a960dd330e8c8401a598bd2f2ec6901100 (patch)
tree952298d9d7d6ecacaf7448ed5a58211f0fa48c2b /src/libstd/thread
parent2d46ae7c37a779fe993687e753b7c544bb26dc38 (diff)
downloadrust-7b6ad7a960dd330e8c8401a598bd2f2ec6901100.tar.gz
rust-7b6ad7a960dd330e8c8401a598bd2f2ec6901100.zip
make park/unpark example more realistic
Diffstat (limited to 'src/libstd/thread')
-rw-r--r--src/libstd/thread/mod.rs19
1 files changed, 15 insertions, 4 deletions
diff --git a/src/libstd/thread/mod.rs b/src/libstd/thread/mod.rs
index 99f8fa390d2..4a5ba9b800e 100644
--- a/src/libstd/thread/mod.rs
+++ b/src/libstd/thread/mod.rs
@@ -827,22 +827,33 @@ const NOTIFIED: usize = 2;
 ///
 /// ```
 /// use std::thread;
+/// use std::sync::{Arc, atomic::{Ordering, AtomicBool}};
 /// use std::time::Duration;
 ///
-/// let parked_thread = thread::Builder::new()
-///     .spawn(|| {
+/// let flag = Arc::new(AtomicBool::new(false));
+/// let flag2 = Arc::clone(&flag);
+///
+/// let parked_thread = thread::spawn(move || {
+///     // We want to wait until the flag is set.  We *could* just spin, but using
+///     // park/unpark is more efficient.
+///     while !flag2.load(Ordering::Acquire) {
 ///         println!("Parking thread");
 ///         thread::park();
 ///         // We *could* get here spuriously, i.e., way before the 10ms below are over!
+///         // But that is no problem, we are in a loop until the flag is set anyway.
 ///         println!("Thread unparked");
-///     })
-///     .unwrap();
+///     }
+///     println!("Flag received");
+/// });
 ///
 /// // Let some time pass for the thread to be spawned.
 /// thread::sleep(Duration::from_millis(10));
 ///
+/// // Set the flag, and let the thread wake up.
 /// // There is no race condition here, if `unpark`
 /// // happens first, `park` will return immediately.
+/// // Hence there is no risk of a deadlock.
+/// flag.store(true, Ordering::Release);
 /// println!("Unpark the thread");
 /// parked_thread.thread().unpark();
 ///