avoid cost of std::mutex when not multi-threading?

前端 未结 7 1402
星月不相逢
星月不相逢 2021-02-19 09:49

Suppose I have an application that may or may not have spawned multiple threads. Is it worth it to protect operations that need synchronization conditionally with a std::mutex a

相关标签:
7条回答
  • 2021-02-19 10:29

    I disagree with wide-spread idea that locking mutext is cheap. If you really are after performance, you wouldn't want to do this.

    Mutexes (even uncontested) hit you with three hummers: they penalize compiler optimizations (mutexes are optimization barriers), they incure memory fences (on un-pessimized platforms) and they are kernel calls. So if you are after nanoseconds performance in tight loops, it is something worth considering.

    Branching is not great, either - for multiple reasons. The real solution is to avoid operatations requiring synchronization in multithread environment. As simple as that.

    0 讨论(0)
提交回复
热议问题