Volatile vs. Interlocked vs. lock

后端 未结 9 1784
悲哀的现实
悲哀的现实 2020-11-22 05:54

Let\'s say that a class has a public int counter field that is accessed by multiple threads. This int is only incremented or decremented.

T

9条回答
  •  梦谈多话
    2020-11-22 06:26

    Interlocked functions do not lock. They are atomic, meaning that they can complete without the possibility of a context switch during increment. So there is no chance of deadlock or wait.

    I would say that you should always prefer it to a lock and increment.

    Volatile is useful if you need writes in one thread to be read in another, and if you want the optimizer to not reorder operations on a variable (because things are happening in another thread that the optimizer doesn't know about). It's an orthogonal choice to how you increment.

    This is a really good article if you want to read more about lock-free code, and the right way to approach writing it

    http://www.ddj.com/hpc-high-performance-computing/210604448

提交回复
热议问题