Created
December 15, 2014 23:00
-
-
Save emk/acdf3ab9c79ba1abe6d2 to your computer and use it in GitHub Desktop.
Multithreaded trait access
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::sync::Arc; | |
use std::sync::RWLock; | |
use std::task::spawn; | |
trait Common : Sized + Send + Sync { | |
fn munge(&mut self); | |
} | |
#[deriving(Show)] | |
struct Foo { i: int } | |
impl Common for Foo { | |
fn munge(&mut self) { | |
self.i += 1; | |
println!("Munging a Foo: {}", self.i); | |
} | |
} | |
#[deriving(Show)] | |
struct Bar { j: int } | |
impl Common for Bar { | |
fn munge(&mut self) { | |
self.j += 1; | |
println!("Munging a Bar: {}", self.j); | |
} | |
} | |
fn main() { | |
let box1 = Arc::new(RWLock::<Box<Common>>::new(box Foo{i: 0})); | |
let box2 = Arc::new(RWLock::<Box<Common>>::new(box Bar{j: 0})); | |
for _ in range(0i, 2) { | |
// Make new handles for our boxes and pass them to a thread. | |
let boxes = vec!(box1.clone(), box2.clone()); | |
spawn(proc() { | |
for b in boxes.iter() { | |
b.write().munge(); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment