Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Thread safe id generation with Interlocked in c#

I am trying to understand Interlocked in C# in thread synchronization.

public int MethodUsedByMultipleThreads()
{
    var id = CreateNextId();
    return id;
}

private long CreateNextId()
{
    long id = 0;
    Interlocked.Exchange(ref id , this._nextId);
    Interlocked.Increment(ref this._nextId);
    return id;
}

Is the line

Interlocked.Exchange(ref id , this._nextId);

redundant if I directly use

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Interlocked.Increment(ref this._nextId);
return _nextId;

Will it serve the same purpose?

>Solution :

The line

Interlocked.Exchange(ref id, this._nextId);

is both redundant and incorrect. It is redundant because it is practically the same as:

id = this._nextId

…because the id is a local variable that is not shared with other threads. And it is incorrect because there is a race condition between incrementing the _nextId field and returning it from the method CreateNextId(). The correct implementation is:

private long CreateNextId()
{
    long id;
    id = Interlocked.Increment(ref this._nextId);
    return id;
}

…or simply:

private long CreateNextId() => Interlocked.Increment(ref this._nextId);

The method Interlocked.Increment increments the _nextId field, and returns the incremented value as an atomic operation.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading