Advertisement
Guest User

Untitled

a guest
May 3rd, 2016
833
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 2.16 KB | None | 0 0
  1. extern crate hyper;
  2. extern crate rustc_serialize;
  3.  
  4. use std::thread;
  5. use std::io::Read;
  6. use std::ops::DerefMut;
  7. use std::sync::Mutex;
  8. use std::sync::MutexGuard;
  9. use std::sync::LockResult;
  10. use std::sync::Arc;
  11.  
  12. use hyper::Client;
  13. use hyper::header::Connection;
  14. use rustc_serialize::json;
  15.  
  16. #[derive(RustcDecodable, RustcEncodable)]
  17. struct Story {
  18.     by: String,
  19.     id: i32,
  20.     score: i32,
  21.     time: i32,
  22.     title: String,
  23. }
  24.  
  25. fn next(cursor: &mut Arc<Mutex<usize>>) -> usize {
  26.     let result: LockResult<MutexGuard<usize>> = cursor.lock();
  27.     let mut guard: MutexGuard<usize> = result.unwrap();
  28.     let mut temp = guard.deref_mut();
  29.     *temp = *temp+1;
  30.     return *temp;
  31. }
  32.  
  33. fn main() {
  34.     let client = Arc::new(Client::new());
  35.     let url = "https://hacker-news.firebaseio.com/v0/topstories.json";
  36.     let mut res = client.get(url).header(Connection::close()).send().unwrap();
  37.     let mut body = String::new();
  38.     res.read_to_string(&mut body).unwrap();
  39.     let vec: Vec<i32> = json::decode(body.as_str()).unwrap();
  40.     let lock: Arc<Mutex<usize>> = Arc::new(Mutex::new(0));
  41.  
  42.     let mut handles: Vec<thread::JoinHandle<()>> = Vec::new();
  43.     for _ in 0..8 {
  44.         let client2 = client.clone();
  45.         let mut lock2 = lock.clone();
  46.         let vec2 = vec.clone();
  47.         handles.push(thread::spawn(move|| {
  48.             loop {
  49.                 let cursor = next(&mut lock2);
  50.  
  51.                 if cursor >= vec2.len() {
  52.                     break;
  53.                 }
  54.  
  55.                 let url = format!(
  56.                     "https://hacker-news.firebaseio.com/v0/item/{}.json",
  57.                     vec2[cursor],
  58.                 );
  59.  
  60.                 let mut res = client2.get(url.as_str())
  61.                     .header(Connection::close())
  62.                     .send()
  63.                     .unwrap();
  64.  
  65.                 let mut body = String::new();
  66.                 res.read_to_string(&mut body).unwrap();
  67.                 let story: Story = json::decode(body.as_str()).unwrap();
  68.                 println!("{}", story.title);
  69.             };
  70.         }));
  71.     }
  72.  
  73.     for handle in handles.into_iter() {
  74.         handle.join().unwrap();
  75.     }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement