线程安全的左移
本文关键字:左移 安全 线程 | 更新日期: 2023-09-27 17:50:48
最明显的方法是使用锁。
但是我知道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
)组合在一起,您就可以自行处理了。