为结构的每个实例生成顺序 ID [英] Generate sequential IDs for each instance of a struct
问题描述
我正在编写一个系统,其中我有一个 Object
的集合,每个 Object
都有一个唯一的完整 ID.这是我在 C++ 中的做法:
I'm writing a system where I have a collection of Object
s, 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;
这显然不是线程安全的,但如果我想要它,我可以将 nextId_
设为 std::atomic_int
,或者在 周围包裹一个互斥锁nextId_++
表达式.
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.
我将如何在(最好是安全的)Rust 中做到这一点?没有静态结构成员,全局可变变量也不安全.我总是可以将 nextId
传递到 new
函数中,但是这些对象将被分配到很多地方,我不想通过管道传递 nextId
号码随处可见.想法?
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?
推荐答案
全局可变变量也不安全
nor are global mutable variables safe
您的 C++ 示例似乎存在线程安全问题,但我对 C++ 的了解不够确定.
Your C++ example seems like it would have thread-safety issues, but I don't know enough C++ to be sure.
然而,只有未同步的全局可变变量是有问题的.如果你不关心跨线程问题,你可以使用线程本地:
However, only unsynchronized global mutable variables are trouble. If you don't care about cross-thread issues, you can use a thread-local:
use std::cell::Cell;
#[derive(Debug)]
struct Monster {
id: usize,
health: u8,
}
thread_local!(static MONSTER_ID: Cell<usize> = Cell::new(0));
impl Monster {
fn new(health: u8) -> Monster {
MONSTER_ID.with(|thread_id| {
let id = thread_id.get();
thread_id.set(id + 1);
Monster { id, health }
})
}
}
fn main() {
let gnome = Monster::new(41);
let troll = Monster::new(42);
println!("gnome {:?}", gnome);
println!("troll {:?}", troll);
}
如果您确实想要更适合多线程的东西,请查看 bluss 的答案,其中显示了如何使用一个原子变量.
If you do want something that works better with multiple threads, check out bluss' answer, which shows how to use an atomic variable.
这篇关于为结构的每个实例生成顺序 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!