Skip to content

Instantly share code, notes, and snippets.

@JSila
Last active July 21, 2020 07:51
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 JSila/9731f60cc03d4db3cbc975019f402f1e to your computer and use it in GitHub Desktop.
Save JSila/9731f60cc03d4db3cbc975019f402f1e to your computer and use it in GitHub Desktop.
Rust: example of using channels to communicate between threads (mutiple producers, single consumer)
use std::sync::mpsc::channel;
use chrono::{DateTime, Local};
use threadpool::ThreadPool;
#[derive(Debug)]
struct Site {
id: String,
url: String,
changed: Option<bool>,
changed_date: Option<DateTime<Local>>
}
#[derive(Debug)]
struct Group {
ids: Vec<String>,
changed: Option<bool>,
changed_date: Option<DateTime<Local>>
}
#[derive(Debug)]
struct Plan {
sites: Vec<Site>,
groups: Vec<Group>
}
fn main() {
let pool = ThreadPool::new(4);
let mut plan = Plan {
sites: vec![
Site { id: "1qwe".to_string(), url: "http 1".to_string(), changed: None, changed_date: None },
Site { id: "3sdf".to_string(), url: "http 2".to_string(), changed: None, changed_date: None },
Site { id: "4321".to_string(), url: "http 3".to_string(), changed: None, changed_date: None },
],
groups: vec![
Group { ids: vec!["1qwe".to_string(), "4321".to_string()], changed: None, changed_date: None }
]
};
let n_sites = plan.sites.len();
let (tx, rx) = channel();
for mut site in plan.sites.into_iter() {
let _tx = tx.clone();
pool.execute(move || {
/* some heavy work to determine if website has changed */
let changed = true;
if changed {
site.changed = Option::from(true);
site.changed_date = Option::from(Local::now());
}
_tx.send(site).unwrap();
});
}
plan.sites = rx.iter()
.take(n_sites)
.collect();
println!("{:?}", plan);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment