Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- extern crate hyper;
- extern crate rustc_serialize;
- use std::thread;
- use std::io::Read;
- use std::ops::DerefMut;
- use std::sync::Mutex;
- use std::sync::MutexGuard;
- use std::sync::LockResult;
- use std::sync::Arc;
- use hyper::Client;
- use hyper::header::Connection;
- use rustc_serialize::json;
- #[derive(RustcDecodable, RustcEncodable)]
- struct Story {
- by: String,
- id: i32,
- score: i32,
- time: i32,
- title: String,
- }
- fn next(cursor: &mut Arc<Mutex<usize>>) -> usize {
- let result: LockResult<MutexGuard<usize>> = cursor.lock();
- let mut guard: MutexGuard<usize> = result.unwrap();
- let mut temp = guard.deref_mut();
- *temp = *temp+1;
- return *temp;
- }
- fn main() {
- let client = Arc::new(Client::new());
- let url = "https://hacker-news.firebaseio.com/v0/topstories.json";
- let mut res = client.get(url).header(Connection::close()).send().unwrap();
- let mut body = String::new();
- res.read_to_string(&mut body).unwrap();
- let vec: Vec<i32> = json::decode(body.as_str()).unwrap();
- let lock: Arc<Mutex<usize>> = Arc::new(Mutex::new(0));
- let mut handles: Vec<thread::JoinHandle<()>> = Vec::new();
- for _ in 0..8 {
- let client2 = client.clone();
- let mut lock2 = lock.clone();
- let vec2 = vec.clone();
- handles.push(thread::spawn(move|| {
- loop {
- let cursor = next(&mut lock2);
- if cursor >= vec2.len() {
- break;
- }
- let url = format!(
- "https://hacker-news.firebaseio.com/v0/item/{}.json",
- vec2[cursor],
- );
- let mut res = client2.get(url.as_str())
- .header(Connection::close())
- .send()
- .unwrap();
- let mut body = String::new();
- res.read_to_string(&mut body).unwrap();
- let story: Story = json::decode(body.as_str()).unwrap();
- println!("{}", story.title);
- };
- }));
- }
- for handle in handles.into_iter() {
- handle.join().unwrap();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement