结合 Interlocked.Increment 和 Interlocked.Exchange [英] Combining Interlocked.Increment and Interlocked.Exchange

查看:56
本文介绍了结合 Interlocked.Increment 和 Interlocked.Exchange的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望以无锁方式原子地递增静态变量并同时将新值分配给实例字段.目标是让每个对象在创建时获得一个唯一的、递增的 id,这样两个对象就没有机会获得相同的 id.

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

推荐答案

你只需要这样做:

orderingId = Interlocked.Increment(ref currentOrderingId);

两个线程不可能接收到相同的值,所以它是线程安全的.

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

这篇关于结合 Interlocked.Increment 和 Interlocked.Exchange的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆