Skip to content

Instantly share code, notes, and snippets.

@gliheng
Created December 4, 2018 11:04
Show Gist options
  • Select an option

  • Save gliheng/8bfbd1a19596a67e6de59eac6c17b9f9 to your computer and use it in GitHub Desktop.

Select an option

Save gliheng/8bfbd1a19596a67e6de59eac6c17b9f9 to your computer and use it in GitHub Desktop.

Revisions

  1. gliheng created this gist Dec 4, 2018.
    86 changes: 86 additions & 0 deletions main.rs
    Original 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());
    }