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

前端 未结 7 1372
星月不相逢
星月不相逢 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:24

    Yes, often avoiding an unnecessary lock with a conditional will improve performance simply because a mutex will normally rely on an RMW or entering the kernel, both of which are relatively expensive to a simple branch. See the double-checked locking idiom for an example of another scenario where avoiding locks can be beneficial.

    However, you always want to consider the cost to benefit. Multi-threaded bugs can creep in when you start special casing for single and multi-threaded code, which can suck to track down. The other thing to consider is that while there may be a measurable difference between eliding the lock and not, it might not be a measurable impact on the software as a whole. So measure, but measure intelligently.

提交回复
热议问题