互锁和挥发性 [英] Interlocked and volatile

查看:233
本文介绍了互锁和挥发性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我使用表示状态的变量。它可以读取并从多个线程写入。

I have a variable which I am using to represent state. It can be read and written to from multiple threads.

我使用 Interlocked.Exchange Interlocked.CompareExchange 来改变它。不过我从多个线程读取它。

I am using Interlocked.Exchange and Interlocked.CompareExchange to change it. However I am reading it from multiple threads.

我知道挥发性可用于确保变量不能在本地缓存,但总是直接从内存中读取。

I know that volatile can be used to make sure the variable is not cached locally but always reads directly from memory.

但是,如果我把它生成一个有关使用挥发性和使用裁判的互锁方法传递警告变量挥发即可。

However if I set the variable to volatile then it generates a warning about using volatile and passing using ref to the Interlocked methods.

我要确保每个线程读取最新变量的值而不是一些缓存的版本,但我不能使用挥发。

I want to ensure that each thread is reading the most recent value of the variable and not some cached version, but I can't use volatile.

有一个 Interlocked.Read ,但它是64位类型和不可用在紧凑的框架。它的文件说,它并不需要32位类型的,因为它们是在一个单一的操作已经完成。

There is a Interlocked.Read but it is for 64 bit types and is not available on the compact framework. The documentation for it says that it is not needed for 32 bit types as they are already performed in a single operation.

有跨你不上网发了言ŧ如果你正在使用的所有接入互锁方法都需要挥发。然而,你不能使用互锁式读取一个32位的变量,所以也没有办法,你可以使用所有的接入互锁方法。

There are statements made across the internet that you don't need volatile if you are using the Interlocked methods for all your access. However you can't read a 32 bit variable using the Interlocked methods, so there is no way you can use Interlocked methods for all your access.

有没有一些方法来完成我的变量的线程安全读写,而无需使用锁?

Is there some way to accomplish the thread safe read and write of my variable without using lock?

推荐答案

当你使用你可以安全地无视警告 Interlocked.Xxx 函数(见的这个问题),因为他们总是这样动荡的操作。因此,一个挥发性变量是共享状态完全确定。如果你想不惜一切代价摆脱的警告,你实际上的可以的做一个联锁阅读Interlocked.CompareExchange(REF计数器,0,0)

You can safely disregard that warning when you're using Interlocked.Xxx functions (see this question), because they always do volatile operations. So a volatile variable is perfectly OK for shared state. If you want to get rid of the warning at all costs, you actually can do an interlocked read with Interlocked.CompareExchange (ref counter, 0, 0).

编辑:其实,你需要挥发性你的状态变量的,如果你要直接写它(即不使用 Interlocked.Xxx )。 作为jerryjvl提到,读取与互锁(或波动)操作更新的变量会使用最新的值。

Actually, you need volatile on your state variable only if you are going to write to it directly (i.e. not using Interlocked.Xxx). As jerryjvl mentioned, reads of a variable updated with an interlocked (or volatile) operation will use the most recent value.

这篇关于互锁和挥发性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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