Designing a Thread Safe Class

前端 未结 6 2146
轮回少年
轮回少年 2021-02-05 11:29

When reading the MSDN documentation it always lets you know if a class is thread safe or not. My question is how do you design a class to be thread safe? I am not talking about

6条回答
  •  爱一瞬间的悲伤
    2021-02-05 12:28

    The documentation doesn't suggest that classes are thread-safe, only methods are. In order to assert that a method is thread-safe, it has to be callable from multiple threads simultaneously without giving incorrect results (where incorrect results would be the method returning the wrong value or the object getting into an invalid state).

    When the documentation says

    Any public static (Shared in Visual Basic) members of this type are thread safe.

    it probably means that the static members of the class do not mutate shared state.

    When the documentation says

    Any instance members are not guaranteed to be thread safe.

    it probably means that methods have minimal internal locking.

    When the documentation says

    All public and protected members of this class are thread-safe and may be used concurrently from multiple threads.

    it probably means that all methods you can call use the appropriate locking within them. It is also possible that the methods do not mutate any shared state, or that it is a lock-free data structure that by-design allows concurrent usage without any locks.

提交回复
热议问题