Create a gist now

Instantly share code, notes, and snippets.

@cocuh /strategy.rs
Last active May 14, 2016

What would you like to do?
strategy pattern on Rust with multi-threading
use std::sync::{Arc, Mutex};
use std::vec::Vec;
trait Queue<T> {
fn new() -> Self where Self: Sized; // required
fn enqueue(&mut self, item: T);
fn dequeue(&mut self) -> Option<T>;
}
#[derive(Debug)]
struct FIFOQueue<T> {
data: Vec<T>,
}
impl<T> Queue<T> for FIFOQueue<T> {
fn new() -> Self {
FIFOQueue { data: Vec::new() }
}
fn enqueue(&mut self, item: T) {
self.data.insert(0, item);
}
fn dequeue(&mut self) -> Option<T> {
self.data.pop()
}
}
#[derive(Debug)]
struct FILOQueue<T> {
data: Vec<T>,
}
impl<T> Queue<T> for FILOQueue<T> {
fn new() -> Self {
FILOQueue { data: Vec::new() }
}
fn enqueue(&mut self, item: T) {
self.data.push(item);
}
fn dequeue(&mut self) -> Option<T> {
self.data.pop()
}
}
type SharableQueue<'a, T> = Queue<T> + 'a + Sized + Send; // important!! SizedとSendが別threadから参照するために必要の様子
struct Searcher {
queue: Arc<Mutex<SharableQueue<'static, usize>>>,
}
impl Searcher {
fn run(&self, thread_num: usize) {
(0..thread_num)
.map(|i| {
let queue = self.queue.clone();
std::thread::spawn(move || {
let item = queue.lock().unwrap().dequeue();
match item {
Some(val) => println!("[thread{}]dequeue {}", i, val),
None => {}
}
})
})
.collect::<Vec<_>>()
.into_iter()
.map(|w| w.join())
.collect::<Vec<_>>();
}
fn set_queue(&mut self, queue: Arc<Mutex<SharableQueue<'static, usize>>>) {
self.queue = queue;
}
}
fn main() {
let fifo = Arc::new(Mutex::new(FIFOQueue::<usize>::new()));
let filo = Arc::new(Mutex::new(FILOQueue::<usize>::new()));
for val in 1..16 {
fifo.lock().unwrap().enqueue(val);
filo.lock().unwrap().enqueue(val);
}
println!("fifo");
println!("{:?}", *fifo.lock().unwrap());
let mut searcher = Searcher { queue: fifo.clone() };
searcher.run(8);
println!("");
println!("filo");
println!("{:?}", *filo.lock().unwrap());
searcher.set_queue(filo.clone());
searcher.run(8);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment