【问题标题】:Why doesn't InterlockedCompareExchange return changed value?为什么 InterlockedCompareExchange 不返回更改的值?
【发布时间】:2011-12-08 05:02:40
【问题描述】:
LONG __cdecl InterlockedCompareExchange(
  __inout  LONG volatile *Destination,
  __in     LONG Exchange,
  __in     LONG Comparand
);

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

只是好奇。
为什么 InterlockedCompareExchange 返回 initial 值?他们这样设计有什么原因吗?

【问题讨论】:

    标签: windows winapi synchronization atomic interlocked


    【解决方案1】:

    因为这可以为您提供最多的信息。如果您只知道更改后的值,并且恰好等于Exchange,则初始值可能是Exchange,也可能是Comparand

    【讨论】:

      【解决方案2】:

      这是来自 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;
          }
      

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

      【讨论】:

      • 你再给我一点解释就更好了。不管怎样,我终于明白了。谢谢。
      猜你喜欢
      • 2013-04-08
      • 2018-06-21
      • 1970-01-01
      • 2014-04-21
      • 2012-12-04
      • 1970-01-01
      • 2014-02-10
      • 1970-01-01
      相关资源
      最近更新 更多