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

前端 未结 7 1911
梦毁少年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:10

    While this is thread-safe, it's not efficient. You could easily make it more efficient by using a shared_mutex (either C++14 or Boost, it's not in C++11). This is because if two threads ask for the size, this should not be a problem. However, if a thread asks for the size and another wanted to add an element, then only one of them should be allowed access.

    So I would change your code like this:

    #include 
    #include 
    #include 
    
    /// A thread-safe vector
    class ThreadSafeVector {
    private:
      mutable std::shared_timed_mutex m; //notice the mutable
      std::vector v;
    
    public:
      // add double to vector
      void add(double d) {
        std::unique_lock lg(m); //just shared_mutex doesn't exist in C++14, you're welcome to use boost::shared_mutex, it's the same
        v.emplace_back(d);
      }
    
      // return length of vector  
      //notice the const, because this function is not supposed to modify your class
      int length() const {
        std::shared_lock lg(m);
        return v.size();
      }   
    };
    

    A few things to keep in mind:

    • std::mutex (and all other mutexes) are non-copyable. This means that your class is now non-copyable. To make it copyable, you have to implement the copy-constructor yourself and bypass copying the mutex.

    • always make your mutexes mutable in containers. This is because modifying a mutex doesn't mean you're modifying the content of the class, which is compatible with the const I added to the length() method. That const means that this method doesn't modify anything within the class. It's a good practice to use it.

提交回复
热议问题