围绕是否写保证锁在另一个线程新鲜读? (.NET,内存模型) [英] Does a lock around a write guarantee fresh read in another thread? (.Net, memory model)

查看:215
本文介绍了围绕是否写保证锁在另一个线程新鲜读? (.NET,内存模型)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个属性,它的制定者是由一个锁保护,但周围没有消气任何锁,如:

Say I have a property whose setter is protected by a lock, but without any lock around the getter, e.g.

private long _myField;
public long MyProperty
{
    get { return _myField; }
    set { lock(whatever) _myField = value; }
}

在除了同步写入(但不读),锁,或者更确切地说Monitor.Exit,应该引起的性写。现在,让我们说,我们有两个线程A和B,以及下列顺序发生:

In addition to synchronizing writes (but not reads), the lock, or rather Monitor.Exit, should cause a volatile write. Let's now say we have two threads A and B, and the following sequence happens:

  1. A读取 myProperty的
  2. 的当前值
  3. 乙写入一个新值 myProperty的
  4. A读取 myProperty的了。
  5. 的当前值
  1. A reads the current value of MyProperty.
  2. B writes a new value to MyProperty.
  3. A reads the current value of MyProperty again.

问:是目前保证看到新的价值?或者是我们的锁只是保证B写入主存储器及时,但不是说其他​​线程读取一个新的价值?或者,可以在答复甚至取决于我们是否在.net 2+或弱ECMA实施运行?

Q: Is A now guaranteed to see the new value? Or did our lock just ensure that B writes to main memory in a timely manner, but not that other threads read a fresh value? Or could the answer even depend on whether we're running in .Net 2+ or a "weaker" ECMA implementation?

推荐答案

没有,因为读没有明确的内存屏障,它不是保证看到新的值。

No, since the read does not have the explicit memory barrier, it is not "guaranteed" to see the new value.

您可以使用 ReaderWriterLockSlim 以确保一)写锁定对方和b)的读取始终皮卡新的价值。

You can use a ReaderWriterLockSlim to insure that a) the writes lock each other and b) the reads always pickup the new value.

private readonly ReaderWriterLockSlim _myFieldLock = new ReaderWriterLockSlim();
private long _myField;
public long MyProperty
{
    get 
    {
        _myFieldLock.EnterReadLock();
        try
        {
            return _myField;
        }
        finally
        {
            _myFieldLock.ExitReadLock();
        }
    }
    set
    {
        _myFieldLock.EnterWriteLock();
        try
        {
            _myField = value;
        }
        finally
        {
            _myFieldLock.ExitWriteLock();
        }
    }
}

这篇关于围绕是否写保证锁在另一个线程新鲜读? (.NET,内存模型)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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