views:

173

answers:

4

Dear ladies and sirs.

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.

+12  A: 

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 to NewGuid 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.

Dan Tao
+5  A: 

Not possible. Static methods of Guid are guaranteed to be thread-safe. See documentation here.

Jesse C. Slicer
They're thread-safe in that the code for `NewGuid` is isolated. The possibility, however slim, still exists for multiple concurrent calls to generate the same Guid.
Austin Salonen
Thanks, updated my question.
mark
+1  A: 

It's not likely to happen...

http://msdn.microsoft.com/en-gb/library/system.guid(v=VS.95).aspx

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.[...]

A GUID is a 128-bit integer (16 bytes) that can be used across all computers and networks wherever a unique identifier is required. Such an identifier has a very low probability of being duplicated.

mamoo
A: 

Well, current implementations of .Net use CoCreateGuid internally

Damien_The_Unbeliever