Advertisement
Guest User

Untitled

a guest
Jun 16th, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.80 KB | None | 0 0
  1. use std::sync::{Mutex};
  2. use std::thread;
  3.  
  4. struct ThreadSafeStruct {
  5. w: Mutex<u64>,
  6. }
  7.  
  8. impl ThreadSafeStruct {
  9. fn update(&self, val: u64) {
  10. let mut v = self.w.lock().unwrap();
  11. *v = val;
  12. }
  13.  
  14. fn get(&self) -> u64 {
  15. let v = self.w.lock().unwrap();
  16. *v
  17. }
  18. }
  19.  
  20. fn main() {
  21. let ilivelongenough: ThreadSafeStruct = ThreadSafeStruct {
  22. w: Mutex::new(200),
  23. };
  24.  
  25. let ilivelongenough_ref = &ilivelongenough;
  26.  
  27. let thread_handle = thread::spawn(move || {
  28.  
  29. println!("Value of ilivelongenough in another thread is: {}.", ilivelongenough_ref.get());
  30.  
  31. thread::sleep(std::time::Duration::from_secs(1));
  32. });
  33.  
  34. thread_handle.join().unwrap_or_default();
  35.  
  36. println!("ilivelongenough in this thread is: {}.", ilivelongenough.get());
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement