Skip to content

Instantly share code, notes, and snippets.

@oconnor663
Last active March 16, 2019 06:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oconnor663/a48b9243b10b16c94a0b09f5e7184263 to your computer and use it in GitHub Desktop.
Save oconnor663/a48b9243b10b16c94a0b09f5e7184263 to your computer and use it in GitHub Desktop.
HN example without crossbeam
use serde::Deserialize;
use std::sync::{Arc, Mutex};
const STORIES_URL: &str = "https://hacker-news.firebaseio.com/v0/topstories.json";
const ITEM_URL_BASE: &str = "https://hacker-news.firebaseio.com/v0/item";
#[derive(Deserialize)]
struct Story {
title: String,
}
fn main() {
let story_ids: Arc<Vec<u64>> = Arc::new(reqwest::get(STORIES_URL).unwrap().json().unwrap());
// AtomicUsize would be simpler than Mutex<usize> here, but the point of
// this is to give a Mutex example.
let cursor = Arc::new(Mutex::new(0));
let mut handles = Vec::new();
for _ in 0..8 {
let cursor = cursor.clone();
let story_ids = story_ids.clone();
handles.push(std::thread::spawn(move || loop {
let index = {
let mut cursor_guard = cursor.lock().unwrap();
let index = *cursor_guard;
if index >= story_ids.len() {
return;
}
*cursor_guard += 1;
index
};
let story_url = format!("{}/{}.json", ITEM_URL_BASE, story_ids[index]);
let story: Story = reqwest::get(&story_url).unwrap().json().unwrap();
println!("{}", story.title);
}));
}
for handle in handles {
handle.join().unwrap();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment