2 回答

TA貢獻1906條經驗 獲得超10個贊
Arc
sleep
Sync
Mutex
Atomic*
范圍-線程池
use scoped_threadpool::Pool; // 0.1.9use std::{thread, time::Duration};fn main() { let mut vec = vec![1, 2, 3, 4, 5]; let mut pool = Pool::new(vec.len() as u32); pool.scoped(|scoped| { for e in &mut vec { scoped.execute(move || { thread::sleep(Duration::from_secs(1)); *e += 1; }); } }); println!("{:?}", vec);}
橫梁
use crossbeam; // 0.6.0use std::{thread, time::Duration};fn main() { let mut vec = vec![1, 2, 3, 4, 5]; crossbeam::scope(|scope| { for e in &mut vec { scope.spawn(move |_| { thread::sleep(Duration::from_secs(1)); *e += 1; }); } }) .expect("A child thread panicked"); println!("{:?}", vec);}
人造絲
use rayon::iter::{IntoParallelRefMutIterator, ParallelIterator}; // 1.0.3use std::{thread, time::Duration};fn main() { let mut vec = vec![1, 2, 3, 4, 5]; vec.par_iter_mut().for_each(|e| { thread::sleep(Duration::from_secs(1)); *e += 1; }); println!("{:?}", vec);}
客戶端必須將連接放在 Arc
當代碼被并行化時,代碼是庫內部的。
Arc
/ Mutex

TA貢獻1777條經驗 獲得超3個贊
Logger
Clone
Arc<Mutex<Connection>>
Connection
Arc
添加回答
舉報