为什么锁是需要实现一个只读整型属性? [英] Why lock is needed to implement a readonly int property?

查看:131
本文介绍了为什么锁是需要实现一个只读整型属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的线程和我在的博客。我粘贴的code只是必要的部分:

I'm new to threading and I came accross a custom thread pool implementation example in a blog. I'm pasting just the necessary parts of the code:

Public Class ThreadPool

    Private CountLock As New Object
    Private _Count As Integer

    Public ReadOnly Property ThreadCount() As Integer
      Get
         SyncLock CountLock
           Return _Count
         End SyncLock
      End Get
    End Property

    Public Sub Open()
      Interlocked.Increment(_Count)
    End Sub

    Public Sub Close()
      Interlocked.Decrement(_Count)
      ....
    End Sub

EndClass

我的问题是,为什么我们需要一个锁来实现只读经纬物业?

My question is, why do we need a lock to implement the readonly ThreadCount property?

推荐答案

锁将迫使内存屏障,使从CPU缓存中陈旧的值,如果写的最后的值是由不同的CPU不被读取。同样可以用 Thread.VolatileRead()进行无锁定。

The lock will force a memory barrier, so that a stale value from the CPU cache isn't read if the last value written was written by a different CPU. The same could be done with Thread.VolatileRead() without locking.

这篇关于为什么锁是需要实现一个只读整型属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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