safe left shift

The obvious way to do it would be with locking.

But I know that there is Interlocked class in c#, which is good for thread safe increment and decrement, so I wondered if there is something like that which would let me do the same for binary operations like left shift.

Is there anything like Interlocked class for left-shift operator?


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

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

The Interlocked class's methods are largely focused on providing thread-safe versions of individual operators in C#. It has methods for operators like += and ++ , which are not thread safe.

Many operators, like << , = , and + , are thread-safe already, so Interlocked doesn't have methods for those. Once you combine those operators with other operators (like x = y + z ), you're pretty much on your own.

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

上一篇: 右操作数为负时按位移运算符的行为

下一篇: 安全左移