显而易见的方法是锁定。
但是我知道Interlocked
c# 中有一个类,这对于线程安全递增和递减很有用,所以我想知道是否有类似的东西可以让我对左移等二进制操作做同样的事情。
Interlocked
左移运算符有什么类似的类吗?
显而易见的方法是锁定。
但是我知道Interlocked
c# 中有一个类,这对于线程安全递增和递减很有用,所以我想知道是否有类似的东西可以让我对左移等二进制操作做同样的事情。
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# 中提供各个运算符的线程安全版本。它具有诸如+=
and之类的运算符的方法++
,这些方法不是线程安全的。
许多运算符,如<<
、=
和+
,已经是线程安全的,因此 Interlocked 没有这些方法。一旦将这些运算符与其他运算符(如x = y + z
)结合起来,您就几乎可以靠自己了。