如何设置在.net中一个最小值,而无需使用锁? [英] How can I set a min value in .Net without using a lock?

查看:94
本文介绍了如何设置在.net中一个最小值,而无需使用锁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在访问变量的多个线程。我知道怎么写自旋锁,并使用Threading.Interlocked方法来增加等变量。

I have multiple threads accessing variables. I know how to write spinlocks and use the Threading.Interlocked methods to increment etc. variables.

不过,我想执行的等效的:

However, I want to perform the equivalent of:

a = Math.Min(a, b)
or
a = a | 10

...但不使用临界区。这可能吗?我知道二号线是可能的汇编程序,但没有Interlocked.Or方法。

... but without using a critical section. Is this possible? I know the 2nd line is possible in assembler, but there is no Interlocked.Or method.

推荐答案

下面是一般模式模拟联锁操作。

Here is the general pattern for simulating an interlocked operation.

public static T InterlockedOperation<T>(ref T location, T value)
{
  T initial, computed;
  do
  {
    initial = location;
    computed = op(initial, value); // initial | value
  } 
  while (Interlocked.CompareExchange(ref location, computed, initial) != initial);
  return computed;
}

的最小操作是一个完全不同的故事。这里的问题是,有在玩两个存储单元。此外,我们只关心阅读。这意味着我们只需要担心内存屏障问题。与装饰你的领域挥发性或做显式调用 Thread.MemoryBarrier 之前计算分。

The min operation is a completely different story. The issue here is that there are two memory locations in play. Furthermore, we are only interested in reading them. That means we really only need to worry about the memory barrier problem. Decorate your fields with volatile or do an explicit call to Thread.MemoryBarrier prior to computing the min.

编辑:我错过了最小操作的结果被分配到的事实。实际上,你可以用我上面定义的模式,但是在做计算=初始|值 DO 计算=初始&LT;值 ?初始:值。其他一切保持不变。

I missed the fact that the result of the min operation is assigned to a. You can actually use the pattern I defined above, but instead of doing computed = initial | value do computed = initial < value ? initial : value. Everything else stays the same.

这篇关于如何设置在.net中一个最小值,而无需使用锁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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