Вопрос

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?

Это было полезно?

Решение

Assuming you are trying to left-shift and assign, and assuming that you do not want collisions, you could do something like this:

// 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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top