Skip to content

Instantly share code, notes, and snippets.

@emk
Created December 15, 2014 23:00
Show Gist options
  • Select an option

  • Save emk/acdf3ab9c79ba1abe6d2 to your computer and use it in GitHub Desktop.

Select an option

Save emk/acdf3ab9c79ba1abe6d2 to your computer and use it in GitHub Desktop.

Revisions

  1. emk created this gist Dec 15, 2014.
    39 changes: 39 additions & 0 deletions multithreaded-traits.rs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,39 @@
    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();
    }
    });
    }
    }