最明显的方法就是锁定。
但是我知道在Interlocked中有c#类,它有利于线程安全的增量和减少,所以我想知道是否有类似的东西可以让我对像左移位这样的二进制操作做同样的事情。
对于左移操作符有类似于Interlocked类的东西吗?
发布于 2014-03-18 23:04:57
假设您正在尝试左移并分配任务,并且假设您不希望发生冲突,您可以这样做:
// 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-18 22:58:57
互锁类的方法主要集中于在C#中提供单个操作符的线程安全版本。它为操作符(如+=和++ )提供了一些方法,它们不是线程安全的。
许多操作符,如<<、=和+,已经是线程安全的了,因此没有用于这些操作的方法。一旦将这些操作符与其他操作符(如x = y + z)结合,您就可以自己动手了。
https://stackoverflow.com/questions/22492676
复制相似问题