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

前端 未结 7 1275
星月不相逢
星月不相逢 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条回答
  •  梦毁少年i
    2021-02-19 10:02

    In general it is possible that it is cheap enough to not worry about it until you are done

    When you are done, then you can profile it both ways and see the impact.

    Keep in mind you will have to profile the effect for both single and multi-threaded. It might effect multi-threaded as well.

    #ifdef USE_CONDITIONAL_GUARDED_MUTEX
    std::atomic more_than_one_thread_active{false};
    #else
    static const bool more_than_one_thread_active{true}; // always use mutex
    #endif
    

    You might want to consider making this a compile time option, and have a single and multi-threaded version of your binary, that way no if is needed

    #ifdef SINGLE_THREADED_WITHOUT_MUTEX
    static const bool more_than_one_thread_active{false}; // never use mutex
    #else
    static const bool more_than_one_thread_active{true}; // always use mutex
    #endif
    

    Almost every optimizer will remove code surrounded by a const bool based on its value

提交回复
热议问题