参考分配是线程安全的吗? [英] Is a reference assignment threadsafe?

查看:87
本文介绍了参考分配是线程安全的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在C#中建立一个多线程缓存,它将保存一个Car对象列表:

 公共静态IList< ;汽车>汽车{get;我想知道在不锁定的情况下更改线程中的引用是否安全吗? 



例如

  private static void Loop()
{
而(true)
{
汽车= GetFreshListFromServer();
Thread.Sleep(SomeInterval);
}
}

基本上,这取决于是否分配新的引用到



如果不是,那么我显然必须为我的汽车使用一个私有字段,并锁定获取和设置。 / p>

解决方案

是的,在语言规范中,参考更新保证是原子的。


5.5变量引用的原子性


以下数据类型的读写是原子的:bool,char,byte,sbyte,short,ushort,uint,int,float和参考类型。此外,上一个列表中具有基础类型的枚举类型的读取和写入也是原子的。不能保证其他类型的读取和写入(包括long,ulong,double和十进制以及用户定义的类型)都是原子的。


但是在紧密循环内,可能会被寄存器缓存咬住。在这种情况下,除非您的方法调用是内联的(可能会发生),否则不太可能。我个人会添加 lock 使其简单易懂,但 volatile 也可以提供帮助。并请注意,完全线程安全不仅仅是原子性。


在使用缓存的情况下,我将查看 Interlocked.CompareExchange 个人-即 try 进行更新,但是如果失败,则从头开始重做 (从新值开始),然后重试。


I'm building a multi threaded cache in C#, which will hold a list of Car objects:

public static IList<Car> Cars {get; private set;}

I'm wondering if it's safe to change the reference in a thread without locking ?

e.g.

private static void Loop()
{
  while (true)
  {
    Cars = GetFreshListFromServer();
    Thread.Sleep(SomeInterval);
  }
}

Basically it comes down to whether assigning a new reference to Cars is atomic or not I'd guess.

If it's not I'll obviously have to use a private field for my cars, and lock around getting and settings.

解决方案

Yes, reference updates are guaranteed to be atomic in the language spec.

5.5 Atomicity of variable references

Reads and writes of the following data types are atomic: bool, char, byte, sbyte, short, ushort, uint, int, float, and reference types. In addition, reads and writes of enum types with an underlying type in the previous list are also atomic. Reads and writes of other types, including long, ulong, double, and decimal, as well as user-defined types, are not guaranteed to be atomic.

However inside a tight loop you might get bitten by register caching. Unlikely in this case unless your method-call is inlined (which might happen). Personally I'd add the lock to make it simple and predictable, but volatile can help here too. And note that full thread-safety is more than just atomicity.

In the case of a cache, I'd be looking at Interlocked.CompareExchange, personally - i.e. try to update, but if it fails redo the work from scratch (starting from the new value) and try again.

这篇关于参考分配是线程安全的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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