C生成唯一的ID [英] C generate unique id

查看:345
本文介绍了C生成唯一的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个可以读取存储在文本文件中的数据结构类型的C包装器。该界面应该是我可以生成一个唯一的ID映射到唯一的数据结构,并通过包装器功能通过唯一的ID进行修改。

I am creating a C wrapper that can read types of data structures stored in text files. The interface should be that I can generate a unique id mapped to a unique data structure and modify through wrapper functions via the unique id.

问题是我需要能够生成唯一的ID来映射。我不想使用任何外部图书馆。有没有任何方法可以做到这一点没有任何大的开销?

The problem is that I need to be able to generate a unique id to map. I would like to not use any external library. Is there any way to do this without any large overhead?

推荐答案

我想你想要的id(实际上)全球独一无二(所以在两台不同机器上的两台不同的计算机上运行程序的两个进程总是有不同的ids)。

I guess that you are wanting the id to be (practically speaking) world-wide unique (so two processes running your program on two different computers on two different machines would always have different ids).

否则,只需使用 static long counter; then id = counter ++; 在你的包装器中

Otherwise, just use a static long counter; then id = counter++; in your wrapper.

您可以为此目的使用 UUID

或者你可以生成一个随机的-eg 24字节 - 字符串(或两个或三个随机 uint64_t 数字)。如果您的数字足够随机(至少如果您将一个随机的 PRNG 种好启动时种子,例如使用随机源àla random(4) 或当前时间和进程标识和主机ID;确保使用足够大状态的PRNG)碰撞应该可以忽略不计(但我不能或愿意量化它)。

Or you could generate a random -e.g. 24 bytes- string (or two or three random uint64_t numbers). If your numbers are "enough" random (at least if you seed a good PRNG with a random seed at startup time, e.g. using a random source à la random(4) or the current time & process id & host id; be sure to use a PRNG with a big enough state) the probability of collisions should be negligible (but I am not able or willing to quantify it).

FWIW,在我的 MELT 监视器中,我在常规的 mom_make_random_idstr中做类似的事情(在Linux上) 我的文件 random.c ;随机字符串包含一个很受限制的字符集(与C标识符兼容)。

FWIW, in my MELT monitor, I am doing similar things (on Linux) in routine mom_make_random_idstr of my file random.c; the random string contains a nicely restricted set of characters (compatible with C identifiers).

您还可以从MongoDb objid

You could also take some inspiration from MongoDb objids.

另请参见此相关问题

这篇关于C生成唯一的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆