2015-06-01 19 views
7

Considerare il codice seguente, desidero generare x thread, che generano richieste x sul server specificato all'interno del codice, tuttavia al momento la mia applicazione è in attesa di ogni thread e di x richieste per terminare prima di girare il prossimo.Thread non in esecuzione in parallelo

Come posso fare per fare questo async? Uscita

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(); 
    } 
} 

Programma:

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 

risposta

8

vostro colpevole è questa linea:

handle.join().unwrap(); 

si esegue un thread nel ciclo, e poi a destra dopo l'avvio della discussione si join che nel filo principale.

Che cosa si potrebbe fare, è creare uno Vec e inserire tutti gli handle nel vec. Quindi, in un altro ciclo, si join tutte le maniglie.

Un'altra possibilità è semplicemente non unire i fili e lasciarli uscire in modo naturale, ma non si saprà quando verranno eseguiti tutti. Il che, come osserva @delnan, potrebbe consentire al thread principale di uscire prima che i thread generati escano. Questo fa sì che tutti i thread spawn vengano uccisi anziché lasciarli eseguire alla fine.

+3

Un problema con il non partecipare ai thread è che (per i non demoni) il processo muore quando il thread principale muore, quindi nel codice OP i thread di lavoro verrebbero interrotti. – delnan

Problemi correlati