Rust 多线程笔记 全面绣化
双核服务器跑10亿累加速度,很快呢!Compiling thread v0.1.0 (/root/rs/thread) Finished `dev` profile target(s) in 0.39s
Running `target/debug/thread`
结果:499999999500000000;耗时:5145 毫秒
结果:499999999500000000;耗时:5223 毫秒
结果:499999999500000000;耗时:4771 毫秒
耗时毫妙:9630
总和为:499999999500000000
耗时毫妙:17798
总和为:499999999500000000
lib.rs
pub mod th1;
th1.rs
use std::time;
use std::sync::{Arc, Mutex, mpsc::channel};
use std::thread::{JoinHandle, spawn, scope};
pub fn elapsed(){
let t = time::Instant::now();
let mut sum = 0u64;
for i in 0..1000000000 {
sum += i;
}
println!("耗时毫妙:{}", t.elapsed().as_millis());
println!("总和为:{}", sum);
}
pub fn elapsed2(){
let t = time::Instant::now();
let mut sum = 0u64;
let _ = (0..1000000000).map(|x| sum+=x).collect::<()>();
println!("耗时毫妙:{}", t.elapsed().as_millis());
println!("总和为:{}", sum);
}
pub fn elapsed_mutex(num: u64){
let t = time::Instant::now();
let chunsize = num / 2;
let mut start: u64;
let mut end: u64;
let sum = Arc::new(Mutex::new(0u64));//共享计数锁
let mut handles: Vec<JoinHandle<_>> = vec![];
for i in 0..2{//两个线程
start = i * chunsize;
if i == 1{
end = num;
}else{
end = (i + 1) * chunsize;
}
//println!("{} - {}", start, end);
let th_inner_lock = Arc::clone(&sum);//创建锁的指针给到线程
handles.push(spawn(move || {
let mut local_sum = 0u64;
for j in start..end{
local_sum += j;
}
*th_inner_lock.lock().unwrap() += local_sum;//线程结果自动释放锁
}))
}
for handle in handles{
handle.join().unwrap();
}
println!("结果:{};耗时:{} 毫秒", sum.lock().unwrap(), t.elapsed().as_millis());
}
pub fn elapsed_channel(num: u64){
let t = time::Instant::now();
let chunsize = num / 2;
let mut start: u64;
let mut end: u64;
let (tx, rx) = channel();//创建多生产者,单消费者 FIFO 队列通信原语
for i in 0..2{
start = i * chunsize;
if i == 1{
end = num;
}else{
end = (i + 1) * chunsize;
}
//println!("{} - {}", start, end);
let th_tx = tx.clone();//创建指针(副本)
spawn(move || {
let mut local_sum = 0u64;
for j in start..end{
local_sum += j;
}
th_tx.send(local_sum).unwrap();//线程结束时丢弃
});
}
drop(tx);//这个发送者需要丢弃,不然会导致接受者阻塞(接受者会等待每个发送者,除非发送者已经丢弃)
let mut sum = 0u64;
while let Ok(t) = rx.recv(){
sum += t;
}
println!("结果:{};耗时:{} 毫秒", sum, t.elapsed().as_millis());
}
pub fn elapsed_scope(num: u64){
let t = time::Instant::now();
let chunsize = num / 2;
let mut start = 0u64;
let mut end = 0u64;
let sum = Mutex::new(0u64);//需要一个锁来同步
scope(|th|{
for i in 0..2{
start = i * chunsize;
if i == 1{
end = num;
}else{
end = (i + 1) * chunsize;
}
//println!("{} - {}", start, end);
let sum_ref = ∑//将将引用给到线程
th.spawn(move ||{
let mut local_sum = 0u64;
for j in start..end{
local_sum += j;
}
*sum_ref.lock().unwrap() += local_sum;
});
}
});
println!("结果:{};耗时:{} 毫秒", sum.lock().unwrap(), t.elapsed().as_millis());
}
main.rs
use std::thread;
use ::thread::th1;
fn main() {
let num = 1000000000;
th1::elapsed_mutex(num);
th1::elapsed_channel(num);
th1::elapsed_scope(num);
let h1 = thread::spawn(th1::elapsed);
let h2 = thread::spawn(th1::elapsed2);
h1.join().unwrap();
h2.join().unwrap();
}
牛的学到了 不错哦,收藏 Rust 这门语言确实强大
页:
[1]