2

我想知道是否可以将以下代码中的初始值重新排序为在计算之后导致未定义的行为。

以下示例取自https://docs.microsoft.com/en-us/dotnet/api/system.threading.interlocked.compareexchange?view=netframework-4.8

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;
    }
}

在将总值分配给初始值和实际计算之间是否需要内存屏障?

正如我目前所理解的,没有障碍可以通过删除导致线程安全问题的初始值的方式进行优化,因为可以使用陈旧的值计算 computedValue,但 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;
    }

此处是否缺少局部变量的特殊规则来解释为什么该示例不使用内存屏障?

4

1 回答 1

0

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 不需要它们的全局可见性。因此,换句话说,在绝大多数情况下,您无需担心局部变量操作的重新排序。

于 2019-05-14T09:47:49.343 回答