2

显而易见的方法是锁定。

但是我知道Interlockedc# 中有一个类,这对于线程安全递增和递减很有用,所以我想知道是否有类似的东西可以让我对左移等二进制操作做同样的事情。

Interlocked左移运算符有什么类似的类吗?

4

2 回答 2

2

假设您尝试左移和分配,并假设您不想要碰撞,您可以执行以下操作:

// this method will only return a value when this thread's shift operation "won" the race
int GetNextValue()
{
    // execute until we "win" the compare
    // might look funny, but you see this type of adjust/CompareAndSwap/Check/Retry very often in cases where the checked operation is less expensive than holding a lock
    while(true)
    {
        // if AValue is a 64-bit int, and your code might run as a 32-bit process, use Interlocked.Read to retrieve the value.
        var value = AValue;
        var newValue = value << 1;
        var result = Interlocked.CompareExchange(ref AValue, newValue, value);
        // if these values are equal, CompareExchange peformed the compare, and we "won" the exchange
        // if they are not equal, it means another thread beat us to it, try again.
        if (result == value)
            return newValue;
    }
}
于 2014-03-18T23:04:57.487 回答
0

Interlocked 类的方法主要侧重于在 C# 中提供各个运算符的线程安全版本。它具有诸如+=and之类的运算符的方法++,这些方法不是线程安全的。

许多运算符,如<<=+,已经是线程安全的,因此 Interlocked 没有这些方法。一旦将这些运算符与其他运算符(如x = y + z)结合起来,您就几乎可以靠自己了。

于 2014-03-18T22:58:57.300 回答