如果一个锁变量声明为volatile? [英] Should a lock variable be declared volatile?

查看:145
本文介绍了如果一个锁变量声明为volatile?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下锁的语句:

 私人只读对象ownerLock_ =新的对象();

锁定(ownerLock_)
{
}
 

我应该使用挥发性的关键字为我的锁变量?

 私人只读挥发物ownerLock_ =新的对象();
 

在MSDN我看到它一般用于指未锁定访问的领域,所以如果我用锁,我不需要使用volatile?

MSDN

  

挥发性改性剂通常用于是受访问的场   多线程不使用lock语句来序列化的访问。

解决方案

如果你的只有的不断访问该锁卫士,而你自己的锁,然后是数据 - 使这些田挥发是多余的。你不需要做 ownerLock _ 变量波动无论是。 (您还没有目前显示的锁定语句,这使得它很难讲具体条款中的任何实际的code - 但我假设你会的实际上的是读/的锁内修改一些数据语句。)

挥发性应的非常的应用code很少使用。如果你想无锁到一个变量访问,互锁几乎总是简单推理。如果你想无锁超越的访问,我几乎总是开始锁定。 (或尝试使用一成不变的数据结构的开始。)

我只希望看到挥发性中的code这是试图建立更高层次的抽象线程 - 所以在第三方物流codeBase的,对于例。这是真正的专家谁的工具真的的理解.NET内存模式彻底......其中也有极少数,海事组织。

I have the following Lock statement:

private readonly object ownerLock_ = new object();

lock (ownerLock_)
{
}

Should I use volatile keyword for my lock variable?

private readonly volatile object ownerLock_ = new object();

On MSDN I saw that it usually used for a field that is accessed without locking, so if I use Lock I don't need to use volatile?

From MSDN:

The volatile modifier is usually used for a field that is accessed by multiple threads without using the lock statement to serialize access.

解决方案

If you're only ever accessing the data that the lock "guards" while you own the lock, then yes - making those fields volatile is superfluous. You don't need to make the ownerLock_ variable volatile either. (You haven't currently shown any actual code within the lock statement, which makes it hard to talk about in concrete terms - but I'm assuming you'd actually be reading/modifying some data within the lock statement.)

volatile should be very rarely used in application code. If you want lock-free access to a single variable, Interlocked is almost always simpler to reason about. If you want lock-free access beyond that, I would almost always start locking. (Or try to use immutable data structures to start with.)

I'd only expect to see volatile within code which is trying to build higher level abstractions for threading - so within the TPL codebase, for example. It's really a tool for experts who really understand the .NET memory model thoroughly... of whom there are very few, IMO.

这篇关于如果一个锁变量声明为volatile?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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