Do we need to lock mutex around std::map<K, V>::find function?

  • A+

Here we are:

template<typename TK, typename TV> class MetaAssociator { public:     void Set(TK key, TV const & value)    {       boost::lock_guard<boost::mutex> lock(m_Mutex);       m_Map[key] = value;    }     TV Get(TK key) const    {       boost::lock_guard<boost::mutex> lock(m_Mutex); // this one       std::map<TK,TV>::const_iterator iter = m_Map.find(key);       return iter == m_Map.end() ? TV() : iter->second;    }  private:    mutable boost::mutex m_Mutex;    std::map<TK,TV> m_Map; }; 

Do we really need to lock mutex in the get function? We are only providing read only access. What if we do not?

Yes, we need it.

Let's suppose 2 threads A and B:

  • The thread A is setting the value.
  • The thread B is reading this value at the same time.

Data races conditions can be produced here, including segmentation fault (thread B is trying to use an object which doesn't exist anymore).

We can use a mutex for protect these sections (like in your example). Another option is to use a read and write lock. The advantage of a read-write lock is that allows concurrent read-access.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: