Created
April 2, 2017 21:41
-
-
Save timvisee/2e47f9615af5b14c2fcf1ae50da8f07f to your computer and use it in GitHub Desktop.
This file contains hidden or 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, Mutex, MutexGuard}; | |
| use std::thread; | |
| use std::time::Duration; | |
| fn main() { | |
| // Create our manager | |
| let manager = MyManager::new(); | |
| // Start a thread that uses the manager's data | |
| manager.start_thread(); | |
| } | |
| // A structure containing data, that we want to wrap in a mutex to 'make' it Sync | |
| pub struct MyStruct { | |
| value: i32, | |
| } | |
| impl MyStruct { | |
| pub fn new(value: i32) -> Self { | |
| MyStruct { | |
| value: value, | |
| } | |
| } | |
| pub fn get(&self) -> &i32 { | |
| &self.value | |
| } | |
| } | |
| // A managing struct, that holds an arc with the mutex | |
| pub struct MyManager { | |
| field: Arc<Mutex<MyStruct>>, | |
| } | |
| impl MyManager { | |
| pub fn new() -> Self { | |
| MyManager { | |
| field: Arc::new(Mutex::new(MyStruct::new(3))), | |
| } | |
| } | |
| pub fn start_thread(&self) { | |
| // Clone the arc wrapping the mutex | |
| let field_arc = self.field.clone(); | |
| thread::spawn(move || { | |
| loop { | |
| println!("Acquiring lock..."); | |
| // Try to create an accessor from the arc, to acquire a lock on the mutex | |
| let _ = Accessor::from(&field_arc); | |
| println!("Lock acquired."); | |
| thread::sleep(Duration::new(1, 0)); | |
| } | |
| }).join().unwrap(); | |
| } | |
| } | |
| // An accessor, that wraps a mutex guard and makes the data accessible through | |
| // helping methods on the accessor. It drops the guard (and it's mutex lock) | |
| // when the accessor is dropped. | |
| pub struct Accessor<'a> { | |
| guard: MutexGuard<'a, MyStruct>, | |
| } | |
| impl<'a> Accessor<'a> { | |
| pub fn new(guard: MutexGuard<'a, MyStruct>) -> Self { | |
| Accessor { | |
| guard: guard, | |
| } | |
| } | |
| pub fn from(data: &'a Mutex<MyStruct>) -> Accessor<'a> { | |
| Self::new(data.lock().unwrap()) | |
| } | |
| // A helper method, to access the data | |
| pub fn value(&self) -> &i32 { | |
| self.guard.get() | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment