Created
December 4, 2018 11:04
-
-
Save gliheng/8bfbd1a19596a67e6de59eac6c17b9f9 to your computer and use it in GitHub Desktop.
Revisions
-
gliheng created this gist
Dec 4, 2018 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,86 @@ #[macro_use] extern crate lazy_static; use std::collections::HashMap; use std::sync::{Mutex, Arc}; use std::thread; lazy_static! { static ref bank: Mutex<HashMap<Man, u32>> = Mutex::new({ let mut m = HashMap::new(); m }); static ref counter: Mutex<u32> = Mutex::new(0); } #[derive(Debug, Hash, PartialEq, Eq)] struct Man { name: String, age: u8, secret: Secret, } unsafe impl Send for Man {} unsafe impl Sync for Man {} #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash,)] struct Secret(*const[u8]); unsafe impl Send for Secret {} unsafe impl Sync for Secret {} fn main() { let secret = vec![3, 2, 1]; let ptr = Box::into_raw(secret.into_boxed_slice()); let s = Secret(ptr); let handle = thread::spawn(move || { let mut guard = bank.lock().unwrap(); let secret = vec![3, 2, 1]; (*guard).insert(Man { name: String::from("juju"), age: 36, secret: s, }, 10000); (*guard).insert(Man { name: String::from("Bill"), age: 40, secret: s, }, 1234); }); handle.join(); let guard = bank.lock().unwrap(); let secret = vec![3, 2, 1]; let money = guard.get(&Man{ name: String::from("juju"), age: 36, secret: s, }); println!("juju has {:?}", money); test(); } fn test() { let mut handles = vec![]; for _ in 0..10 { let handle = thread::spawn(move || { let mut num = counter.lock().unwrap(); *num += 1; }); handles.push(handle); } for handle in handles { handle.join().unwrap(); } println!("Result: {}", *counter.lock().unwrap()); }