Thread-safe static variables without mutexing?

前端 未结 5 1189
无人及你
无人及你 2021-02-19 10:32

I remember reading that static variables declared inside methods is not thread-safe. (See What about the Meyer\'s singleton? as mentioned by Todd Gardner)

Dog* M         


        
5条回答
  •  鱼传尺愫
    2021-02-19 11:03

    The only way I know of to guarantee you won't have threading issues with non-protected resources like your "static Dog" is to make it a requirement that they're all instantiated before any threads are created.

    This could be as simple as just documenting that they have to call a MyInit() function in the main thread before doing anything else. Then you construct MyInit() to instantiate and destroy one object of each type that contains one of those statics.

    The only other alternative is to put another restriction on how they can use your generated code (use Boost, Win32 threads, etc). Either of those solutions are acceptable in my opinion - it's okay to generate rules that they must follow.

    If they don't follow the rules as set out by your documentation, then all bets are off. The rule that they must call an initialization function or be dependent on Boost is not unreasonable to me.

提交回复
热议问题