반응형

 

int ddd = Interlocked.CompareExchange(ref _lockecd, desired, expected);

 

 

CompareExchange 이걸 풀어보면

 

if( _lockecd == expected )

{

   _lockecd  = desired;

  return expected;

}else{

 return _locked;

}

 

같으면 expected 를 리턴하고

다르면 _locked 를 리턴한다

 

그리고 같으면 _locked 가 desired 값으로 바뀐다

 

 

그래서 아래 코드는 값이 바뀔때까지 계속 실행된다

 

 

 

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

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

 

주석 설명들에 어떤것과 어떤것이 비교가 되는지 빠져 있어 헷갈린다

ms 홈페이지 설명글은 항상 느끼는 거지만 글자만 있지 내용을 파악하기엔 내용이 부실하게 빠져 있거나 부족하거나 이상한 부분들이 많다

 

 

ref : https://learn.microsoft.com/ko-kr/dotnet/api/system.threading.interlocked.compareexchange?view=net-7.0

반응형

+ Recent posts