- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我想知道是否有可能将以下代码中的初始值重新排序为在计算之后导致未定义的行为。
public class ThreadSafe
{
// Field totalValue contains a running total that can be updated
// by multiple threads. It must be protected from unsynchronized
// access.
private float totalValue = 0.0F;
// The Total property returns the running total.
public float Total { get { return totalValue; }}
// AddToTotal safely adds a value to the running total.
public float AddToTotal(float addend)
{
float initialValue, computedValue;
do
{
// Save the current running total in a local variable.
initialValue = totalValue;
//Do we need a memory barrier here??
// Add the new value to the running total.
computedValue = initialValue + addend;
// CompareExchange compares totalValue to initialValue. If
// they are not equal, then another thread has updated the
// running total since this loop started. CompareExchange
// does not update totalValue. CompareExchange returns the
// contents of totalValue, which do not equal initialValue,
// so the loop executes again.
}
while (initialValue != Interlocked.CompareExchange(ref totalValue,
computedValue, initialValue));
// If no other thread updated the running total, then
// totalValue and initialValue are equal when CompareExchange
// compares them, and computedValue is stored in totalValue.
// CompareExchange returns the value that was in totalValue
// before the update, which is equal to initialValue, so the
// loop ends.
// The function returns computedValue, not totalValue, because
// totalValue could be changed by another thread between
// the time the loop ends and the function returns.
return computedValue;
}
}
在将 totalvalue 分配给 initialvalue 和实际计算之间是否需要内存屏障?
正如我目前所理解的那样,可以在没有障碍的情况下以消除导致线程安全问题的初始值的方式进行优化,因为计算值可以使用陈旧值进行计算,但 CompareExchange 将不再检测到这一点:
public float AddToTotal(float addend)
{
float computedValue;
do
{
// Add the new value to the running total.
computedValue = totalValue + addend;
// CompareExchange compares totalValue to initialValue. If
// they are not equal, then another thread has updated the
// running total since this loop started. CompareExchange
// does not update totalValue. CompareExchange returns the
// contents of totalValue, which do not equal initialValue,
// so the loop executes again.
}
while (totalValue != Interlocked.CompareExchange(ref totalValue,
computedValue, totalValue));
// If no other thread updated the running total, then
// totalValue and initialValue are equal when CompareExchange
// compares them, and computedValue is stored in totalValue.
// CompareExchange returns the value that was in totalValue
// before the update, which is equal to initialValue, so the
// loop ends.
// The function returns computedValue, not totalValue, because
// totalValue could be changed by another thread between
// the time the loop ends and the function returns.
return computedValue;
}
这里是否缺少局部变量的特殊规则来解释为什么示例不使用内存屏障?
最佳答案
CPU 永远不会以可能影响单线程执行逻辑的方式“重新排序”指令。万一
initialValue = totalValue;
computedValue = initialValue + addend;
第二个操作肯定是依赖于上一个操作中设置的值。 CPU 从其单线程逻辑角度“理解”这一点,因此该序列永远不会重新排序。然而,以下序列可以重新排序:
initialValue = totalValue;
anotherValue = totalValue;
或
varToInitialize = someVal;
initialized = true;
如您所见,单核执行不会受到影响,但在多核上这可能会带来一些问题。例如,如果我们围绕这样一个事实构建我们的逻辑,即如果变量 initialized
设置为 true
那么 varToInitialize
应该用某个值初始化,我们可以在多核环境中遇到麻烦:
if (initialized)
{
var storageForVal = varToInitialize; // can still be not initalized
...
// do something with storageForVal with assumption that we have correct value
}
至于局部变量。重新排序的问题是全局可见性的问题,即一个核心/CPU 对其他核心/CPU 所做的更改的可见性。局部变量主要倾向于只对单线程可见(除了一些罕见的情况,比如闭包,在方法之外公开的情况下实际上不是局部变量)所以其他线程无法访问它们并且因此其他核心/CPU 不需要它们的全局可见性。所以换句话说,在绝大多数情况下,您无需担心局部变量操作的重新排序。
关于c# - Interlocked.CompareExchange 指令重新排序初始值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56126472/
我希望以原子方式递增静态变量,同时以无锁方式将新值分配给实例字段。目标是让每个对象在创建时获得一个唯一的、递增的 ID,这样两个对象就不可能获得相同的 ID。 下面的代码能实现吗? class MyC
我在优化程序时遇到了一些奇怪的性能结果,这些结果显示在以下 BenchmarkDotNet 基准测试中: string _s, _y = "yo"; [Benchmark] public void E
很抱歉问了这么长的问题,但是有 Jon Skeet 的引用资料,所以对某些人来说可能是值得的。 简而言之: Interlocked.Read/Interlocked.Exchange 在 Mono 框
在我阅读 ReaderWriterLockSlim 时锁机构,There was this guy谁建议 Interlock函数可用于更精细的锁定 另外,我发现 here马克的另一个回答: ...Wr
假设我有一个变量“counter”,并且有几个线程使用Interlocked访问和设置“counter”的值,即: int value = Interlocked.Increment(ref coun
Interlocked.CompareExchange() 方法 ( docs ) 粗略地说: “我有一个变量,我想我知道它当前有什么值。如果我是对的,请将值更改为那个”。 关键是这个方法可以用来在多
例子: Thread a: Interlocked.Increment(ref x); Thread b: int currentValue = x; 假设线程 b 在线程 a 之后执行,线程 b
我们有一个方法可以维护我们应用程序中所有事件的全局序列索引。由于它是网站,因此预计具有线程安全的这种方法。线程安全的实现如下: private static long lastUsedIndex =
我见过很多不错的对象池实现。例如:C# Object Pooling Pattern implementation . 但似乎线程安全的总是使用锁,从不尝试使用 Interlocked.* 操作。 编
是 Interlocked.Increment(ref x)比 x++ 快或慢对于各种平台上的整数和多头? 最佳答案 它较慢,因为它强制操作以原子方式发生,并且充当内存屏障,消除了处理器围绕指令重新排
我有一个应用程序,它不断地(+-100 毫秒)从 PLC 读取订单,然后将它们放入模型中,然后由多个客户端读取。为此,我使用了 lock 语句。 订单阅读线程: lock (model) { //up
我们有一个并发的多线程程序。我如何使样本数每次增加 +5 间隔? Interlocked.Increment 是否有间隔过载?我没有看到它列出。 Microsoft Interlocked.Incre
作为一个线程菜鸟,我正在尝试找到一种不锁定对象的方法,允许我将线程池任务排入队列,这样它的最大并行度 = 1。 这段代码会按照我的想法行事吗? private int status; private
这仅涉及 Microsoft/Visual Studio 和 Intel/AMD 特定实现。 比如说,如果声明一个全局变量: volatile __declspec(align(16)) ULONG
我有几个简单的(希望是)问题,我一直无法找到答案 - 假设我有多个线程可以访问的对象 a、b。 Interlocked.Exchange(ref a, b) 如果“b”不是 volatile 的,这个
我正在编写一个需要使用 Interlocked 的通用类。 T test1, test2; Interlocked.Exchange(ref test1, test2); 这不会编译。所以我是否被迫使
我有一些遗留代码使用 Interlocked.Equals 来比较值。这些值可以是两个 bool 值,也可以将一个结构数组与 null 进行比较。 Resharper 提示 Interlocked.E
如果我要使用某种算法,在 C++ 中对变量使用 InterlockCompareExchange 操作来确定特定线程是否正在写入一组数据(通过创建我自己的小锁),我如何确保如果数据存储在 i7 上的
假设我们有这样一个类: public class Foo { private Bar bar = new Bar(); public void DoStuffInThread1()
来自文档 here :“此类的方法有助于防止在线程正在更新可由其他线程访问的变量时调度程序切换上下文时可能发生的错误...” 此外,对 this question 的回答声明“互锁方法在任何数量的内核
我是一名优秀的程序员,十分优秀!