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
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