C generate unique id

我们两清 提交于 2019-12-12 04:51:49

问题


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.

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?


回答1:


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).

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

You might use UUIDs for that purpose.

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, 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).

You could also take some inspiration from MongoDb objids.

See also this related question.



来源:https://stackoverflow.com/questions/27250067/c-generate-unique-id

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!