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

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

    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.

提交回复
热议问题