Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
930 views
in Technique[技术] by (71.8m points)

rust - Generate sequential IDs for each instance of a struct

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++:

class Object {
public:
  Object(): id_(nextId_++) { }

private:
  int id_;
  static int nextId_;
}

int Object::nextId_ = 1;

This is obviously not thread_safe, but if I wanted it to be, I could make nextId_ an std::atomic_int, or wrap a mutex around the nextId_++ expression.

How would I do this in (preferably safe) Rust? There's no static struct members, nor are global mutable variables safe. I could always pass nextId into the new function, but these objects are going to be allocated in a number of places, and I would prefer not to pipe the nextId number hither and yon. Thoughts?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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::<Vec<_>>();

    for t in threads {
        println!("{:?}", t.join().unwrap());
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...