Ivan
Ivan

Reputation: 7746

Unique integer multiple threads

I am trying to generate unique integer Ids that can be used from multiple threads.

public partial class Form1 : Form
{
    private static int sharedInteger;
    ...

private static int ModifySharedIntegerSingleTime()
{
    int unique = Interlocked.Increment(ref sharedInteger);

    return unique;
}

SimulateBackTestRow1()
{
    while (true)
    {
        int num = ModifySharedIntegerSingleTime();
    }
}
SimulateBackTestRow2()
{
    while (true)
    {
        int num = ModifySharedIntegerSingleTime();
    }
}

Task modifyTaskOne = Task.Run(() => SimulateBackTestRow1());
Task modifyTaskTwo = Task.Run(() => SimulateBackTestRow2());

However, when code that takes a unique number that has not been used before gets passed a number that was acquired by ModifySharedIntegerSingleTime, I am getting collisions with numbers that are not unique.

What is the correct way to get unique int Ids in a thread-safe way?

Upvotes: 0

Views: 198

Answers (1)

Servy
Servy

Reputation: 203821

You only have 2^32 unique values with an integer. Since you're generating values as quickly as you can in a loop, it wont take you long to generate more than the ~4 billion values you need to have run out and start returning values you've already used and causing collisions. Either you have some bug in your program that results in you generating more new values than you actually need, or you need to use a type that has more values, such as a long or GUID.

Upvotes: 4

Related Questions