1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
/// # 线程同步 /// /// Basic usage: 线程之间传递可变字符 /// /// 该代码存在数据竞争 /// /// ```rust /// use std::thread; /// fn main() { /// let mut s = "Hello".to_string(); /// for _ in 0..3 { /// thread::spawn(move || { /// s.push_str(" Rust!"); /// }); /// } /// } /// ``` /// /// Basic usage: 使用Rc<T>共享所有权 /// /// Rc<T>不能用于多线程共享 /// /// ```rust /// use std::thread; /// use std::rc::Rc; /// fn main() { /// let mut s = Rc::new("Hello".to_string()); /// for _ in 0..3 { /// let mut s_clone = s.clone(); /// thread::spawn(move || { /// s_clone.push_str(" hello"); /// }); /// } /// } /// ``` /// /// Basic usage: 使用Arc<T>共享所有权 /// /// Arc<T>内部不可变,所以报错 /// /// ```rust /// use std::thread; /// use std::sync::Arc; /// fn main() { /// let s = Arc::new("Hello".to_string()); /// for _ in 0..3 { /// let s_clone = s.clone(); /// thread::spawn(move || { /// s_clone.push_str(" world!"); /// }); /// } /// } /// ``` /// /// Basic usage: 使用RefCell支持内部可变 /// /// RefCell<String>没有实现Sync,报错 /// /// ```rust /// use std::thread; /// use std::sync::Arc; /// use std::cell::RefCell; /// fn main() { /// let s = Arc::new(RefCell::new("Hello".to_string())); /// for _ in 0..3 { /// let s_clone = s.clone(); /// thread::spawn(move || { /// let s_clone = s_clone.borrow_mut(); /// s_clone.push_str(" world!"); /// }); /// } /// } /// ``` /// /// Basic usage: 使用Metux /// /// /// ```rust /// use std::thread; /// use std::sync::{Arc, Mutex}; /// fn main() { /// let s = Arc::new(Mutex::new("Hello".to_string())); /// let mut v = vec![]; /// for _ in 0..3 { /// let s_clone = s.clone(); /// let child = thread::spawn(move || { /// let mut s_clone = s_clone.lock().unwrap(); /// s_clone.push_str(" world!"); /// }); /// v.push(child); /// } /// for child in v { /// child.join().unwrap(); /// } /// } /// ``` /// /// Basic usage: 跨线程恐慌“中毒”示例 /// /// 线程在获得锁之后发生恐慌 /// /// ```rust /// use std::sync::{Arc, Mutex}; /// use std::thread; /// fn main() { /// let mutex = Arc::new(Mutex::new(1)); /// let c_mutex = mutex.clone(); /// let _ = thread::spawn(move || { /// let mut data = c_mutex.lock().unwrap(); /// *data = 2; /// panic!("oh no"); /// }).join(); /// assert_eq!(mutex.is_poisoned(), true); /// match mutex.lock() { /// Ok(_) => unreachable!(), /// Err(p_err) => { /// let data = p_err.get_ref(); /// println!("recovered: {}", data); /// } /// }; /// } /// ``` /// /// /// Basic usage: 投掷硬币示例 /// /// 不会死锁 /// /// ```rust /// extern crate rand; /// use std::thread; /// use std::sync::{Arc, Mutex}; /// fn main() { /// let total_flips = Arc::new(Mutex::new(0)); /// let completed = Arc::new(Mutex::new(0)); /// let runs = 8; /// let target_flips = 10; /// for _ in 0..runs { /// let total_flips = total_flips.clone(); /// let completed = completed.clone(); /// thread::spawn(move || { /// flip_simulate(target_flips, total_flips); /// let mut completed = completed.lock().unwrap(); /// *completed += 1; /// }); /// } /// loop { /// let completed = completed.lock().unwrap(); /// if *completed == runs { /// let total_flips = total_flips.lock().unwrap(); /// println!("Final average: {}", *total_flips / *completed); /// break; /// } /// } /// } /// /// fn flip_simulate(target_flips: u64, total_flips: Arc<Mutex<u64>>) { /// let mut continue_positive = 0; /// let mut iter_counts = 0; /// while continue_positive <= target_flips { /// iter_counts += 1; /// let pro_or_con = rand::random(); /// if pro_or_con { /// continue_positive += 1; /// } else { /// continue_positive = 0; /// } /// } /// println!("iter_counts: {}", iter_counts); /// let mut total_flips = total_flips.lock().unwrap(); /// *total_flips += iter_counts; /// } /// ``` /// /// Basic usage: 投掷硬币示例 /// /// 死锁 /// /// ```rust /// extern crate rand; /// use std::thread; /// use std::sync::{Arc, Mutex}; /// fn main() { /// let total_flips = Arc::new(Mutex::new(0)); /// let completed = Arc::new(Mutex::new(0)); /// let runs = 8; /// let target_flips = 10; /// for _ in 0..runs { /// let total_flips = total_flips.clone(); /// let completed = completed.clone(); /// thread::spawn(move || { /// flip_simulate(target_flips, total_flips); /// let mut completed = completed.lock().unwrap(); /// *completed += 1; /// }); /// } /// loop { /// let completed = completed.lock().unwrap(); /// while *completed < runs {} /// let total_flips = total_flips.lock().unwrap(); /// println!("Final average: {}", *total_flips / *completed); /// } /// } /// /// fn flip_simulate(target_flips: u64, total_flips: Arc<Mutex<u64>>) { /// let mut continue_positive = 0; /// let mut iter_counts = 0; /// while continue_positive <= target_flips { /// iter_counts += 1; /// let pro_or_con = rand::random(); /// if pro_or_con { /// continue_positive += 1; /// } else { /// continue_positive = 0; /// } /// } /// println!("iter_counts: {}", iter_counts); /// let mut total_flips = total_flips.lock().unwrap(); /// *total_flips += iter_counts; /// } /// ``` /// /// Basic usage: 读写锁示例 /// /// /// ```rust /// use std::sync::RwLock; /// fn main() { /// let lock = RwLock::new(5); /// { /// let r1 = lock.read().unwrap(); /// let r2 = lock.read().unwrap(); /// assert_eq!(*r1, 5); /// assert_eq!(*r2, 5); /// } /// { /// let mut w = lock.write().unwrap(); /// *w += 1; /// assert_eq!(*w, 6); /// } /// } /// ``` /// /// Basic usage: 屏障示例 /// /// /// ```rust /// use std::sync::{Arc, Barrier}; /// use std::thread; /// fn main() { /// let mut handles = Vec::with_capacity(5); /// let barrier = Arc::new(Barrier::new(5)); /// for _ in 0..5 { /// let c = barrier.clone(); /// handles.push(thread::spawn(move|| { /// println!("before wait"); /// c.wait(); /// println!("after wait"); /// })); /// } /// for handle in handles { /// handle.join().unwrap(); /// } /// } /// ``` /// /// Basic usage: 条件变量 /// /// /// ```rust /// use std::sync::{Arc, Condvar, Mutex}; /// use std::thread; /// fn main() { /// let pair = Arc::new((Mutex::new(false), Condvar::new())); /// let pair_clone = pair.clone(); /// thread::spawn(move || { /// let &(ref lock, ref cvar) = &*pair_clone; /// let mut started = lock.lock().unwrap(); /// *started = true; /// cvar.notify_one(); /// }); /// let &(ref lock, ref cvar) = &*pair; /// let mut started = lock.lock().unwrap(); /// while !*started { /// println!("{}", started); // false /// started = cvar.wait(started).unwrap(); /// println!("{}", started); // true /// } /// } /// ``` pub fn thread_safe(){ unimplemented!(); }