Is there any advantage of using volatile keyword in contrast to use the Interlocked class?

后端 未结 5 1884
时光取名叫无心
时光取名叫无心 2021-02-04 15:59

In other words, can I do something with a volatile variable that could not also be solved with a normal variable and the Interlocked class?

5条回答
  •  逝去的感伤
    2021-02-04 16:37

    Yes - you can look at the value directly.

    As long as you ONLY use the Interlocked class to access the variable then there is no difference. What volatile does is it tells the compiler that the variable is special and when optimizing it shouldn't assume that the value hasn't changed.

    Takes this loop:

    bool done = false;
    
    ...
    
    while(!done)
    {
    ... do stuff which the compiler can prove doesn't touch done...
    }
    

    If you set done to true in another thread you would expect the loop to exit. However - if done is not marked as volatile then the compiler has the option to realize that the loop code can never change done and it can optimize out the compare for exit.

    This is one of the difficult things about multithread programming - many of the situations which are problems only come up in certain situations.

提交回复
热议问题