use std::sync::{Arc, Condvar, Mutex}; use std::thread;
fnmain() { let pair = Arc::new((Mutex::new(false), Condvar::new())); let pair2 = Arc::clone(&pair);
thread::spawn(move || { let (lock, cvar) = &*pair2; // #2 letmut started = lock.lock().unwrap(); *started = true; // We notify the condvar that the value has changed. cvar.notify_one(); });
// Wait for the thread to start up. let (lock, cvar) = &*pair; // #1 letmut started = lock.lock().unwrap(); // As long as the value inside the `Mutex<bool>` is `false`, we wait. while !*started { // #3 started = cvar.wait(started).unwrap(); } }
#3 下面的 wait 方法理解
首先来分析下官网对于 wait 方法的解释
Blocks the current thread until this condition variable receives a notification. This function will atomically unlock the mutex specified (represented by guard) and block the current thread. This means that > any calls to notify_one or notify_all which happen logically after the mutex is unlocked are candidates to wake this thread up. When this function call returns, the lock specified will have been re-acquired.
这句话个人觉得关键点就在于
This function will atomically unlock the mutex specified (represented by guard) and block the current thread.
use std::sync::{Arc, Condvar, Mutex}; use std::thread; use std::time;
fnmain() { let pair = Arc::new((Mutex::new(false), Condvar::new())); let pair2 = Arc::clone(&pair);
thread::spawn(move || { let (lock, cvar) = &*pair2; println!("触发事件"); cvar.notify_one();
thread::sleep(time::Duration::from_secs(4));
println!("线程内获取锁"); letmut started = lock.lock().unwrap(); *started = true;
println!("线程内锁被释放"); });
// Wait for the thread to start up. let (lock, cvar) = &*pair; letmut started = lock.lock().unwrap(); // As long as the value inside the `Mutex<bool>` is `false`, we wait. while !*started { println!("调用 wait 之前"); started = cvar.wait(started).unwrap(); println!("接收到 wait 已触发"); } }
// Wait for the thread to start up. let (lock, cvar) = &*pair; letmut started = lock.lock().unwrap(); // As long as the value inside the `Mutex<bool>` is `false`, we wait. while !*started { println!("调用 wait 之前"); started = cvar.wait(started).unwrap(); println!("接收到 wait 已触发"); } }