2011-12-08 27 views
0
LONG __cdecl InterlockedCompareExchange(
    __inout LONG volatile *Destination, 
    __in  LONG Exchange, 
    __in  LONG Comparand 
); 

返回值
该函数返回目的地参数的初始值。为什么InterlockedCompareExchange没有返回更改值?

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

回答

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

你明白为什么它能够保留初始值是非常重要的?

+1

如果你给我多一点解释会更好。无论如何,我终于明白了。谢谢。 – Benjamin

4

因为这给了你最多的信息。如果您只知道更改后的值,并且它恰好等于Exchange,则初始值可能为Exchange或它为Comparand