明显的做法是锁定。
但是我知道c#中有Interlocked
类,这对于线程安全递增和递减是有好处的,所以我想知道是否有类似的东西可以让我对左移等二进制操作做同样的事情
对于左移运算符,有Interlocked
类吗?
答案 0 :(得分: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;
}
}
答案 1 :(得分:0)
Interlocked类的方法主要侧重于在C#中提供单个运算符的线程安全版本。它有+=
和++
等运算符的方法,这些方法不是线程安全的。
许多运营商(例如<<
,=
和+
)已经是线程安全的,因此Interlocked没有针对这些运营商的方法。将这些运算符与其他运算符(如x = y + z
)组合在一起后,您就可以自己动手了。