在C ++中生成唯一ID的算法? [英] Algorithm for generating a unique ID in C++?

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

问题描述

在C ++中生成唯一ID的最佳算法是什么?
长度ID应为32位无符号整数。

What can be the best algorithm to generate a unique id in C++? The length ID should be a 32 bit unsigned integer.

推荐答案

获取唯一的32位ID直观简单: 下一个。工程40亿次。独特的136年,如果你需要一秒。魔鬼在细节:什么是前一个?你需要一个可靠的方法来保持最后使用的值和一个原子的方式来更新它。

Getting a unique 32-bit ID is intuitively simple: the next one. Works 4 billion times. Unique for 136 years if you need one a second. The devil is in the detail: what was the previous one? You need a reliable way to persist the last used value and an atomic way to update it.

这将取决于ID的范围有多难。如果它是一个进程中的一个线程,那么你只需要一个文件。如果它是一个进程中的多个线程,那么你需要一个文件和互斥。如果是一个机器上的多个进程,那么您需要一个文件和一个命名的互斥体。如果它是多个机器上的多个进程,那么您需要分配一个权威的ID提供程序,一个所有机器与之通信的单个服务器。数据库引擎是一个常见的提供程序,它们具有内置的功能和自动增量列。

How hard that will be depends on the scope of the ID. If it is one thread in one process then you only need a file. If it is multiple threads in one process then you need a file and a mutex. If is multiple processes on one machine then you need a file and a named mutex. If it is multiple processes on multiple machines then you need to assign a authoritative ID provider, a single server that all machines talk to. A database engine is a common provider like that, they have this built-in as a feature, an auto-increment column.

获取ID的费用逐步上升随着范围的扩大。当它变得不切实际,范围是互联网或提供者太慢或不可用,那么你需要放弃一个32位的值。切换到随机值。一个是随机的,使得机器被流星击中的可能性至少比重复相同的ID一百万倍。 goo-ID。它只是4倍大。

The expense of getting the ID goes progressively up as the scope widens. When it becomes impractical, scope is Internet or provider too slow or unavailable then you need to give up on a 32-bit value. Switch to a random value. One that's random enough to make the likelihood that the machine is struck by a meteor is at least a million times more likely than repeating the same ID. A goo-ID. It is only 4 times as large.

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

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