sleep_sort

This commit is contained in:
2020-05-01 21:20:13 +08:00
parent 521b23770c
commit a37d39572f

View File

@@ -1,14 +1,19 @@
use std::{ thread, time::Duration, }; use std::{
thread,
sync::{ Arc, Mutex, },
time::Duration,
};
// sleep sort fn sleep_sort(in_vec: Vec<u8>) -> Vec<u8> {
fn main() { let out_vec = Arc::new(Mutex::new(vec![]));
let in_vec = vec![2, 1, 5, 10, 7];
let mut all_threads = vec![]; let mut all_threads = vec![];
for i in in_vec { for i in in_vec {
let o_vec = out_vec.clone();
let child = thread::spawn(move || { let child = thread::spawn(move || {
thread::sleep(Duration::from_millis(i)); thread::sleep(Duration::from_millis(i as u64));
println!(">> {}", i); let mut v = o_vec.lock().unwrap();
v.push(i);
}); });
all_threads.push(child); all_threads.push(child);
} }
@@ -16,5 +21,18 @@ fn main() {
t.join().ok(); t.join().ok();
} }
let v = out_vec.lock().unwrap();
v.to_vec()
}
// sleep sort
fn main() {
let in_vec = vec![2, 1, 5, 10, 7];
let out_vec = sleep_sort(in_vec);
out_vec.iter().for_each(|i| println!("{}", i));
println!("Finished!"); println!("Finished!");
} }