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
添加回答
举报