我需要的挥发性元素的数组,并不能找到一个方法来做到这一点。
私人挥发性T [] _arr;
这意味着该_arr参考是挥发性的,但它并不能保证有关_arr对象本身内部的物品的任何
有没有什么办法,以纪念_arr的项目为挥发性?
感谢。
编辑:
按二进制codeR的回答内置下面code。 这是code线程安全使用?
公共类VolatileArray< T>
{
私人T [] _arr;
公共VolatileArray(INT长度)
{
_arr =新T [长度];
}
公共VolatileArray(T [] ARR)
{
_arr = ARR;
}
公共牛逼这个[INT指数]
{
得到
{
t值= _arr [指数]
Thread.MemoryBarrier();
返回值;
}
组
{
Thread.MemoryBarrier();
_arr [指数] =值;
}
}
公众诠释长度
{
{返回_arr.Length; }
}
}
解决方案
由于可以通过引用传递数组元素,你可以使用 Thread.VolatileRead
和 Thread.VolatileWrite
。
要明白,挥发性
关键字用在幕后工作 Thread.MemoryBarrier
这是非常有用的。你可以写:
//读取
X = _arr [I];
Thread.MemoryBarrier();
// 写
Thread.MemoryBarrier();
_arr [I] = X;
注意挥发性
和 MemoryBarrier
是先进的技术,既容易出错。例如,看到http://stackoverflow.com/questions/1787450/how-do-i-understand-read-memory-barriers-and-volatile.通常,你最好采用更高级别的结构,如锁定
,显示器
, ReaderWriterLockSlim
,和其他人。
I need an array with volatile items, and can't find a way to do that.
private volatile T[] _arr;
This means that the _arr reference is volatile, however it does not guarantee anything about the items inside the _arr object itself.
Is there any way to mark the _arr's Items as volatile?
Thanks.
EDIT:
The following code built according to binarycoder's answer. Is this code thread-safe to use?
public class VolatileArray<T>
{
private T[] _arr;
public VolatileArray(int length)
{
_arr = new T[length];
}
public VolatileArray(T[] arr)
{
_arr = arr;
}
public T this[int index]
{
get
{
T value = _arr[index];
Thread.MemoryBarrier();
return value;
}
set
{
Thread.MemoryBarrier();
_arr[index] = value;
}
}
public int Length
{
get { return _arr.Length; }
}
}
解决方案
Since it is possible to pass array elements by reference, you can use Thread.VolatileRead
and Thread.VolatileWrite
.
It is useful to understand that the volatile
keyword works behind the scenes by using Thread.MemoryBarrier
. You could write:
// Read
x = _arr[i];
Thread.MemoryBarrier();
// Write
Thread.MemoryBarrier();
_arr[i] = x;
Note that volatile
and MemoryBarrier
are advanced techniques that are both easy to get wrong. For example, see http://stackoverflow.com/questions/1787450/how-do-i-understand-read-memory-barriers-and-volatile. Usually you are better off with higher level constructs such as lock
, Monitor
, ReaderWriterLockSlim
, and others.