同一进程的两个线程可以产生相同的 GUID 吗?
如果进程中的两个线程使用 .NET API (Guid.NewGuid()
) 同时生成一个新的 GUID,这两个 GUID 是否可能相同?
谢谢。
更新 我想变得实用。我知道人们普遍认为 GUID 对于所有实际目的都是唯一的。我想知道是否可以以相同的方式处理同一进程的不同线程生成的 GUIDS。
If two threads in a process generate a new GUID concurrently using .NET API (Guid.NewGuid()
) is it possible that the two GUIDs will be identical?
Thanks.
UPDATE
I want to get practical. I know that it is widely assumed that GUIDs are unique for all practical purposes. I am wondering if I can treat GUIDS produced by the different threads of the same process in the same manner.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
简短回答
可能(例如,在宇宙的一生中,它曾经会发生吗)?是的。
可能(全部)?否。
更长的答案
Microsoft 使用 版本 4 算法 来生成 GUID(另请参阅:此处),它产生一个完全(伪)随机数。
鉴于可能的 GUID 数量,重复的概率很小。就像,小得不可思议。
您关心并发性:幸运的是,
NewGuid
方法是 线程安全,这意味着它要么锁定要么利用线程静态随机数生成器来实现其目的。第一种方法将有效地序列化对 NewGuid 的所有调用,以便它们按顺序发生(绝不同时),而后者将从彼此独立的单独线程进行调用。无论哪种情况,您必须担心从同时创建随机数的两个线程中获取重复项(无论是否为 GUID),是线程使用的底层生成器是否正在运行 (1)来自相同的种子(这只能是由于设计缺陷造成的),和 (2) 以时间相关的方式(版本 4 GUID 算法则不然)。
所以,是的,实际上,您可以将单独线程同时生成的 GUID 视为唯一的。
Short Answer
Possible (as in, could it ever happen, in the lifetime of the universe)? Yes.
Likely (at all)? No.
Longer Answer
Microsoft utilizes a Version 4 algorithm for generating GUIDs (see also: here), which produces a completely (pseudo-)random number.
Given the number of possible GUIDs, the probability of a duplicate is tiny. Like, unfathomably tiny.
You are concerned with concurrency: fortunately, the
NewGuid
method is thread-safe, which means it either locks or utilizes a thread-static random number generator for its purposes. The first approach would effectively serialize all calls toNewGuid
so that they occur in sequence (never simultaneously) while the latter would make calls from separate threads independent of one another.In either case, the only reason you would have to fear getting duplicates from two threads creating random numbers simultaneously --
GUID
or not -- would be if the underlying generators used by the threads were operating (1) from the same seed (which could only result from a design flaw), and (2) in a time-dependent manner (which the version 4 GUID algorithm does not).So yes, practically speaking, you can treat GUIDs generated concurrently from separate threads to be unique.
不可能。
Guid
的静态方法保证是线程安全的。请参阅此处的文档。Not possible. Static methods of
Guid
are guaranteed to be thread-safe. See documentation here.这不太可能发生...
http ://msdn.microsoft.com/en-gb/library/system.guid(v=VS.95).aspx
It's not likely to happen...
http://msdn.microsoft.com/en-gb/library/system.guid(v=VS.95).aspx
好吧,.Net 的当前实现使用 CoCreateGuid内部:
Well, current implementations of .Net use CoCreateGuid internally: