multithreading - Threads not running in parallel -


consider following code, wish spin x threads, fire x requests specified server within code, @ current, application waiting each thread , x requests finish before spinning next one.

how can go doing async?

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()));      _x in 0..100 {         println!("spinning thread...");          let mut client = client::new();         let thread_items = requests.clone();          let handle = thread::spawn(move || {             _x in 0..100 {                 println!("firing 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 thread... firing request firing request firing request firing request spinning thread... firing request firing request firing request firing request spinning thread... firing request firing request firing request firing request 

your culprit line:

handle.join().unwrap(); 

you execute thread in loop, , right after starting thread join main thread.

what do, create vec , put handles in vec. then, in loop, join handles.

another possibility not join threads, , let them exit naturally, won't know when of them done. which, @delnan notes, might allow main thread exit before spawned threads exit. causes spawned threads killed instead of letting them run termination.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -