为什么InterlockedCompareExchange没有返回更改的值?

问题描述 投票:0回答:2
LONG __cdecl InterlockedCompareExchange(
  __inout  LONG volatile *Destination,
  __in     LONG Exchange,
  __in     LONG Comparand
);

返回值 该函数返回Destination参数的初始值。

只是好奇。 为什么InterlockedCompareExchange会返回初始值?他们设计的原因是否有原因?

windows winapi synchronization atomic interlocked
2个回答
1
投票

以下是MSDN的一个很好的例子:

http://msdn.microsoft.com/en-us/library/windows/desktop/ms683560%28v=vs.85%29.aspx

    for(;;)
    {
        // calculate the function
        new_value = Random(old_value);

        // set the new value if the current value is still the expected one
        cur_value = InterlockedCompareExchange(seed, new_value, old_value);

        // we found the expected value: the exchange happened
        if(cur_value == old_value)
            break;

        // recalculate the function on the unexpected value
        old_value = cur_value;
    }

你明白为什么能够保留初始值很重要吗?


5
投票

因为这可以为您提供最多的信息。如果你只知道改变的值并且恰好等于Exchange,那么初始值可能是Exchange或者它可能是Comparand

© www.soinside.com 2019 - 2024. All rights reserved.