Rozważmy następujący kod, chcę rozkręcić x wątków, które będą uruchamiać żądania x na podany serwer w kodzie, jednak w chwili obecnej moja aplikacja czeka na każdy wątek i x żądań do zakończenia przed zakręceniem następnego.Wątki nie działają równolegle
Jak mogę zrobić to asynchronicznie? Wyjście
extern crate hyper;
extern crate time;
use hyper::Client;
use hyper::header::Connection;
use time::*;
use std::thread;
use std::sync::{Arc, Mutex};
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:
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
Jednym z problemów z brakiem dołączania wątków jest to, że (dla nie-demonów) proces umiera, gdy główny wątek ginie, więc w kodzie OP wątki robocze zostałyby skrócone. – delnan