Last active
February 28, 2021 02:11
-
-
Save namachan10777/56f2c464b9bf86ac88cf90cc92165c32 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::{process::exit, sync::{Arc, RwLock}}; | |
use std::sync::mpsc; | |
use std::thread; | |
use std::time::SystemTime; | |
use std::time::Duration; | |
use std::collections::HashMap; | |
use rand::prelude::*; | |
type DB = Arc<RwLock<HashMap<String, Arc<RwLock<usize>>>>>; | |
fn handle(sender: mpsc::Sender<(String, usize)>, db: DB) { | |
let tasks = vec!["John Doe".to_owned(), "Haskell Curry".to_owned(), "Alan Turing".to_owned()]; | |
let mut count = 0; | |
loop { | |
if count >= tasks.len() { | |
break; | |
} | |
{ | |
if let Some(rlock) = db.read().unwrap().get(&tasks[count]) { | |
let ran = *rlock.read().unwrap(); | |
sender.send((tasks[count].to_owned(), ran)).unwrap(); | |
count += 1; | |
continue; | |
} | |
} | |
{ | |
let doc_lock = Arc::new(RwLock::new(0)); | |
let doc_lock_w = doc_lock.clone(); | |
let mut wlock = doc_lock_w.write().unwrap(); | |
{ | |
let mut wlock = db.write().unwrap(); | |
if wlock.contains_key(&tasks[count]) { | |
continue; | |
} | |
wlock.insert(tasks[count].clone(), doc_lock); | |
} | |
thread::sleep(Duration::from_secs(3)); | |
let value = rand::random(); | |
*wlock = value; | |
count += 1; | |
} | |
} | |
} | |
fn main() { | |
let db = Arc::new(RwLock::new(HashMap::new())); | |
let (sender, reciever) = mpsc::channel(); | |
let sender1 = sender.clone(); | |
let sender2 = sender.clone(); | |
let sender3 = sender.clone(); | |
let db0 = db.clone(); | |
let db1 = db.clone(); | |
let db2 = db.clone(); | |
let db3 = db.clone(); | |
thread::spawn(|| { | |
handle(sender, db0); | |
}); | |
thread::spawn(|| { | |
handle(sender1, db1); | |
}); | |
thread::spawn(|| { | |
handle(sender2, db2); | |
}); | |
thread::spawn(|| { | |
handle(sender3, db3); | |
}); | |
let mut count = 0; | |
loop { | |
if count >= 9 { | |
break; | |
} | |
if let Ok((name, value)) = reciever.recv() { | |
count += 1; | |
println!("{} : {}", name, value); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment