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
You are on the right track - write the functional part withot synchronization and add it externally, if and when needed.
Instead of the explicit if
-block I would still instantiate the lock, and hide the complexity in there.
template
struct faster_lock{
faster_lock(Mutex& mutex) lock here, possibly with nested RAII {}
~faster_lock()noexcept { unlock here, or nested RAII }
};
{
faster_lock lock(mutex);
operation_requiring_synchronization();
}
And the last note - if you have atomic flag anyway you can just turn it into a spinlock and keep your logic simpler.