简体   繁体   中英

Combining Interlocked.Increment and Interlocked.Exchange

I wish to atomically increment a static variable and simultaneously assign the new value to an instance field in a lock-free manner. The objective is for each object to get a unique, incrementing id upon creation, such that there is no chance for two objects to get the same id.

Will the following code achieve this?

class MyClass
{
    private static int currentOrderingId;
    private int orderingId;

    public MyClass()
    {
        Interlocked.Exchange(ref orderingId, Interlocked.Increment(ref currentOrderingId));
    }
}

You only need to do this:

orderingId = Interlocked.Increment(ref currentOrderingId);

There's no way that two threads could then receive the same value, so it is threadsafe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM