Interlocked and volatile

后端 未结 2 2063
眼角桃花
眼角桃花 2020-12-12 20:11

I have a variable which I am using to represent state. It can be read and written to from multiple threads.

I am using Interlocked.Exchange and In

2条回答
  •  猫巷女王i
    2020-12-12 21:06

    You can safely disregard that warning when you're using Interlocked.Xxx functions (see this question), because they always do volatile operations. So a volatile variable is perfectly OK for shared state. If you want to get rid of the warning at all costs, you actually can do an interlocked read with Interlocked.CompareExchange (ref counter, 0, 0).

    Edit: Actually, you need volatile on your state variable only if you are going to write to it directly (i.e. not using Interlocked.Xxx). As jerryjvl mentioned, reads of a variable updated with an interlocked (or volatile) operation will use the most recent value.

提交回复
热议问题