Combining Interlocked.Increment and Interlocked.Exchange

£可爱£侵袭症+ 提交于 2020-06-23 08:23:27

问题


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));
    }
}

回答1:


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.



来源:https://stackoverflow.com/questions/51442857/combining-interlocked-increment-and-interlocked-exchange

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!