问题描述
的 System.Threading.Interlocked
对象允许加(减)和比较作为一个原子操作。看来,一个CompareExchange,只是没有做平等也GREATERTHAN /每种不超过作为一个原子比较是很有价值的。
The System.Threading.Interlocked
object allows for Addition (subtraction) and comparison as an atomic operation. It seems that a CompareExchange that just doesn't do equality but also GreaterThan/LessThan as an atomic comparison would be quite valuable.
请问一个假设 Interlocked.GreaterThan
白细胞介素的特点还是一个CPU级别的功能?两者都是?
Would a hypothetical Interlocked.GreaterThan
a feature of the IL or is it a CPU-level feature? Both?
由于缺乏任何其他选项,是有可能创造在C ++这样的功能或直接IL代码和公开该功能为C#?
Lacking any other option, is it possible to create such a feature in C++ or direct IL code and expose that functionality to C#?
推荐答案
更新到后来的文章,我在这里提出:我们找到了一个更好的办法,使通过使用额外的锁对象的更大的比较。我们为了验证锁和互锁可以一起使用,但仅限于某些情况下,写了许多单元测试
Update to the later post I made here: we found a better way to make the greater comparison by using additional lock object. We wrote many unit tests in order to validate that a lock and Interlocked can be used together, but only for some cases.
如何代码工作:互锁使用内存壁垒一个读或写是原子。需要同步锁,使大于比较一个原子操作。所以规则是现在,这个类里面没有其他的操作将没有这个同步锁的价值。
How the code works: Interlocked uses memory barriers that a read or write is atomic. The sync-lock is needed to make the greater-than comparison an atomic operation. So the rule now is that inside this class no other operation writes the value without this sync lock.
我们得到这个类是可以很读取的互锁值速度快,但写操作多一点点。阅读是我们的应用程序要快2-4倍。
What we get with this class is an interlocked value which can be read very fast, but write takes a little bit more. Read is about 2-4 times faster in our application.
下面的代码视图:
看这里: http://files.thekieners.com/blogcontent/2012/ExchangeIfGreaterThan2.png
下面的代码复制并放;贴:密封
Here as code to copy&paste:
public sealed class InterlockedValue
{
private long _myValue;
private readonly object _syncObj = new object();
public long ReadValue()
{
// reading of value (99.9% case in app) will not use lock-object,
// since this is too much overhead in our highly multithreaded app.
return Interlocked.Read(ref _myValue);
}
public bool SetValueIfGreaterThan(long value)
{
// sync Exchange access to _myValue, since a secure greater-than comparisons is needed
lock (_syncObj)
{
// greather than condition
if (value > Interlocked.Read(ref _myValue))
{
// now we can set value savely to _myValue.
Interlocked.Exchange(ref _myValue, value);
return true;
}
return false;
}
}
}
这篇关于Interlocked.CompareExchange<&诠释GT;使用GREATERTHAN或每种不超过,而不是平等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!