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

后端 未结 5 1995
时光取名叫无心
时光取名叫无心 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:34

    Yes, you can gain some performance by using a volatile variable instead of a lock.

    Lock is a full memory barrier which can give you the same characteristics of a volatile variable as well as many others. As has already been said volatile just ensures that in multi-threaded scenarios if a CPU changes a value in its cache line, the other CPUs sees the value immediately but do not ensure any locking semantic at all.

    The thing is lock is a lot more powerful than volatile and you should use volatile when you can to avoid unnecessary locks.

提交回复
热议问题