Generate sequential IDs for each instance of a struct

后端 未结 2 1941
一整个雨季
一整个雨季 2020-12-10 13:26

I\'m writing a system where I have a collection of Objects, and each Object has a unique integral ID. Here\'s how I would do it in C++:

<         


        
2条回答
  •  隐瞒了意图╮
    2020-12-10 13:46

    Atomic variables can live in statics, so you can use it relatively straightforwardly (the downside is that you have global state).

    Example code: (playground link)

    use std::{
        sync::atomic::{AtomicUsize, Ordering},
        thread,
    };
    
    static OBJECT_COUNTER: AtomicUsize = AtomicUsize::new(0);
    
    #[derive(Debug)]
    struct Object(usize);
    
    impl Object {
        fn new() -> Self {
            Object(OBJECT_COUNTER.fetch_add(1, Ordering::SeqCst))
        }
    }
    
    fn main() {
        let threads = (0..10)
            .map(|_| thread::spawn(|| Object::new()))
            .collect::>();
    
        for t in threads {
            println!("{:?}", t.join().unwrap());
        }
    }
    

提交回复
热议问题