2

それを行う明白な方法は、ロックを使用することです。

しかし、c# にはスレッド セーフなインクリメントとデクリメントに適したクラスがあることを知っているInterlockedので、左シフトのようなバイナリ操作でも同じことができるようなものがあるかどうか疑問に思いました。

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 に答える