Thread-safe vector: Is this implementation thread-safe?

前端 未结 7 1919
梦毁少年i
梦毁少年i 2021-01-16 13:22

I have a question regarding the term thread-safety. Let me give an example:

#include 
#include 

/// A thread-safe vector
class Th         


        
7条回答
  •  星月不相逢
    2021-01-16 14:17

    IMHO:

    This is both safe and useful:

      void add(double d) {
        std::lock_guard lg(m);
        v.emplace_back(d);
      }
    

    This is safe but useless:

      // return length of vector  
      int length() {
        std::lock_guard lg(m);
        return v.size();
      }   
    

    Because by the time you've got your length it may well have changed, so reasoning about it is unlikely to be useful.

    How about this?

    template
    decltype(auto) do_safely(Func&& f)
    {
      std::lock_guard lock(m);
      return f(v);
    }
    

    called like this:

    myv.do_safely([](auto& vec) { 
      // do something with the vector
      return true;  // or anything you like
    });
    

提交回复
热议问题