Volatile vs. Interlocked vs. lock

后端 未结 9 1780
悲哀的现实
悲哀的现实 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 06:22

    lock(...) works, but may block a thread, and could cause deadlock if other code is using the same locks in an incompatible way.

    Interlocked.* is the correct way to do it ... much less overhead as modern CPUs support this as a primitive.

    volatile on its own is not correct. A thread attempting to retrieve and then write back a modified value could still conflict with another thread doing the same.

提交回复
热议问题