Why don't my Rust threads work in parallel?

I want to unwind X threads that will run X requests to the specified server in code. My application is currently waiting for each thread and X requests to complete, and then it starts the next one.

How can I do this asynchronously?

extern crate hyper; extern crate time; use hyper::header::Connection; use hyper::Client; use std::sync::{Arc, Mutex}; use std::thread; use time::*; struct Request { elapsed_time: f64, } impl Request { fn new(elapsed_time: f64) -> Request { Request { elapsed_time: elapsed_time, } } } fn main() { let requests = Arc::new(Mutex::new(Vec::new())); for _x in 0..100 { println!("Spinning up thread..."); let mut client = Client::new(); let thread_items = requests.clone(); let handle = thread::spawn(move || { for _x in 0..100 { println!("Firing the request"); let start = time::precise_time_s(); let _res = client .get("http://jacob.uk.com") .header(Connection::close()) .send() .unwrap(); let end = time::precise_time_s(); thread_items .lock() .unwrap() .push((Request::new(end - start))); } }); handle.join().unwrap(); } } 

Program Output:

 Spinning up thread... Firing request Firing request Firing request Firing request Spinning up thread... Firing request Firing request Firing request Firing request Spinning up thread... Firing request Firing request Firing request Firing request 
+8
multithreading asynchronous rust
source share
1 answer

Your culprit is the line:

 handle.join().unwrap(); 

You execute the thread in a loop, and then immediately after starting the join thread in the main thread.

What you can do is create a Vec and put all the descriptors in vec. Then, in another loop, you join all the descriptors.

Another possibility is simply not to join the threads and allow them to exit naturally, but then you will not know when they will all be executed. Which, as @delnan notes, can allow the main thread to exit before the generated threads exit. This leads to the destruction of all generated threads instead of allowing them to work until completion.

+11
source share

All Articles