安全左移

做到这一点的显而易见的方式是锁定。

但是我知道c#中有Interlocked类,这对于线程安全的递增和递减是很好的,所以我想知道是否有类似于左移的二进制操作可以做同样的事情。

是否有类似左移操作符的Interlocked类?


假设你试图左移和分配,并假设你不想碰撞,你可以这样做:

// 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;
    }
}

Interlocked类的方法主要集中在为C#中的各个运算符提供线程安全版本。 它有像+=++这样的运算符的方法,它们不是线程安全的。

许多运算符(如<<=+已经是线程安全的,因此Interlocked没有这些方法。 一旦你将这些操作符与其他操作符(如x = y + z )结合起来,你就可以独立完成操作。

链接地址: http://www.djcxy.com/p/72501.html

上一篇: safe left shift

下一篇: C#/.net bitwise shift left operation over a short[]