首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >螺纹安全左移

螺纹安全左移
EN

Stack Overflow用户
提问于 2014-03-18 22:48:13
回答 2查看 199关注 0票数 2

最明显的方法就是锁定。

但是我知道在Interlocked中有c#类,它有利于线程安全的增量和减少,所以我想知道是否有类似的东西可以让我对像左移位这样的二进制操作做同样的事情。

对于左移操作符有类似于Interlocked类的东西吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-03-18 23:04:57

假设您正在尝试左移并分配任务,并且假设您不希望发生冲突,您可以这样做:

代码语言:javascript
复制
// 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;
    }
}
票数 2
EN

Stack Overflow用户

发布于 2014-03-18 22:58:57

互锁类的方法主要集中于在C#中提供单个操作符的线程安全版本。它为操作符(如+=++ )提供了一些方法,它们不是线程安全的。

许多操作符,如<<=+,已经是线程安全的了,因此没有用于这些操作的方法。一旦将这些操作符与其他操作符(如x = y + z)结合,您就可以自己动手了。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22492676

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档