What Makes a Method Thread-safe? What are the rules?

前端 未结 4 1760
一个人的身影
一个人的身影 2020-11-29 14:52

Are there overall rules/guidelines for what makes a method thread-safe? I understand that there are probably a million one-off situations, but what about in general? Is it t

4条回答
  •  伪装坚强ぢ
    2020-11-29 15:27

    There is no hard and fast rule.

    Here are some rules to make code thread safe in .NET and why these are not good rules:

    1. Function and all functions it calls must be pure (no side effects) and use local variables. Although this will make your code thread-safe, there is also very little amount of interesting things you can do with this restriction in .NET.
    2. Every function that operates on a common object must lock on a common thing. All locks must be done in same order. This will make the code thread safe, but it will be incredibly slow, and you might as well not use multiple threads.
    3. ...

    There is no rule that makes the code thread safe, the only thing you can do is make sure that your code will work no matter how many times is it being actively executed, each thread can be interrupted at any point, with each thread being in its own state/location, and this for each function (static or otherwise) that is accessing common objects.

提交回复
热议问题