如何在Python类中跨多个进程创建唯一的ID

2024-05-17 19:45:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我想写一个对象,在实例化时,为每个实例生成一个新的ID。但此ID必须

  • 以线程和进程安全的方式生成
  • 即使跨进程也是唯一的(通过多进程产生)

一些无关紧要的问题:

  • 这个特定的对象创建不是性能关键的,因此由此带来的同步开销是可以接受的。在
  • id不能是串行的,尽管通常会有一个干净的解决方案。在
  • 我们太无知了,根本不关心Python2。在

已经有一些解决方案只适用于one process,最优雅的是使用itertools.count()对象。使用id()不是选项,因为它不能保证是唯一的。理想的解决方案可能是与itertools.count()类似的对象,它在进程之间保存一些静态全局值。在

关于我们项目的相关讨论:https://github.com/coala-analyzer/coala/issues/981


Tags: 对象实例coalaid进程count方式解决方案
1条回答
网友
1楼 · 发布于 2024-05-17 19:45:37

按照@VPfB的建议,使用UUID。UUID是Universally Unique Identifier的缩写。从技术上讲,id只能与用于存储它们的可用位空间一样唯一。传统的UUID是128位的。Wikipedia article on the topic discusses their uniqueness

To put these numbers into perspective, the annual risk of a given person being hit by a meteorite is estimated to be one chance in 17 billion, which means the probability is about 0.00000000006 (6 × 10−11), equivalent to the odds of creating a few tens of trillions of UUIDs in a year and having one duplicate. In other words, only after generating 1 billion UUIDs every second for the next 100 years, the probability of creating just one duplicate would be about 50%.

另一种解决方案是使用专用系统生成序列(类似于数据库生成主键)。这个系统基本上是一个防弹柜台。当某个东西需要一个ID时,它会向系统查询下一个可用的ID。当系统收到一个新ID的查询时,它会增加计数器并提供新值。它将被安排为更新计数器、获取新值并存储当前状态(针对诸如电源故障等问题)的操作是原子的。在

计数器系统的思想可能不实用,例如在连接不良的分布式系统中。这是需要UUID的主要情况:能够在多个不同的、未连接的系统中生成id,并且极有可能不会发生冲突。在

相关问题 更多 >