Reputation: 3447
I wish to spin up X threads which will fire X requests to the specified server within the code. Currently, my application is waiting for each thread and X requests to finish before spinning up the next one.
How can I go about doing this async?
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
Upvotes: 9
Views: 2181
Reputation: 31283
Your culprit is this line:
handle.join().unwrap();
You execute a thread in the loop, and then right after starting the thread you join
it into the main thread.
What you could do, is to create a Vec
and put all the handles in the vec. Then, in another loop, you join
all the handles.
Another possibility is to simply not join the threads, and let them exit naturally, but then you won't know when all of them are done. Which, as @delnan notes, might allow the main thread to exit before the spawned threads exit. This causes all the spawned threads to be killed instead of letting them run to termination.
Upvotes: 13