Volatile vs. Interlocked vs. lock

后端 未结 9 1592
悲哀的现实
悲哀的现实 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:02

    I would like to add to mentioned in the other answers the difference between volatile, Interlocked, and lock:

    The volatile keyword can be applied to fields of these types:

    • Reference types.
    • Pointer types (in an unsafe context). Note that although the pointer itself can be volatile, the object that it points to cannot. In other words, you cannot declare a "pointer" to be "volatile".
    • Simple types such as sbyte, byte, short, ushort, int, uint, char, float, and bool.
    • An enum type with one of the following base types: byte, sbyte, short, ushort, int, or uint.
    • Generic type parameters known to be reference types.
    • IntPtr and UIntPtr.

    Other types, including double and long, cannot be marked "volatile" because reads and writes to fields of those types cannot be guaranteed to be atomic. To protect multi-threaded access to those types of fields, use the Interlocked class members or protect access using the lock statement.

提交回复
热议问题