小编Cry*_*vat的帖子

使用.NET中的Interlocked类实现按位运算

我正在尝试在多线程.NET应用程序中的共享变量中设置位标志,但无法找到与托管的Interlocked类中的本机InterlockedOr函数的并行.我已经提出了以下用于执行| =赋值的代码,但无限循环的理论可能性让我感到不舒服:

long currentValue;
long updatedValue;

do
{
    // Spin until successful update. Value must be read using Interlocked.Read()
    // to be truly atomic on 32 bit systems (see MSDN).
    currentFlags = Interlocked.Read(ref _currentFlags);
    updatedValue = currentFlags | flag;
} while (currentFlags != Interlocked.CompareExchange(ref _currentFlags, updatedValue, currentFlags));
Run Code Online (Sandbox Code Playgroud)

是否可以仅使用Interlocked类中内置的函数以更安全的方式实现?如果可能的话,我想避免涉及显式锁定的解决方案.

.net c# multithreading bit-manipulation interlocked

8
推荐指数
1
解决办法
467
查看次数

标签 统计

.net ×1

bit-manipulation ×1

c# ×1

interlocked ×1

multithreading ×1