How to use a std::mutex in a class context

后端 未结 2 1039
生来不讨喜
生来不讨喜 2021-02-14 20:18

i\'m having some trouble using a C++11 std::mutex

in my class I have a variable called semaphore of type std::mutex.

So I positioned my semaphore.lock() and sema

2条回答
  •  清歌不尽
    2021-02-14 20:39

    std::mutex is neither copyable nor movable. Including one in your class necessitates that your class becomes non-copyable (-movable) as well. If you want your class to be copyable or movable, you will have to tell the compiler how objects of your class are to be copied or moved by implementing copy/move construction/assignment yourself. For example:

    class synchronized_int {
      mutable std::mutex mtx;
      int value;
    public:
      synchronized_int(int v = 0) : value(v) {}
    
      // Move initialization
      synchronized_int(synchronized_int&& other) {
        std::lock_guard lock(other.mtx);
        value = std::move(other.value);
        other.value = 0;
      }
    
      // Copy initialization
      synchronized_int(const synchronized_int& other) {
        std::lock_guard lock(other.mtx);
        value = other.value;
      }
    
      // Move assignment
      synchronized_int& operator = (synchronized_int&& other) {
        std::lock(mtx, other.mtx);
        std::lock_guard self_lock(mtx, std::adopt_lock);
        std::lock_guard other_lock(other.mtx, std::adopt_lock);
        value = std::move(other.value);
        other.value = 0;
        return *this;
      }
    
      // Copy assignment
      synchronized_int& operator = (const synchronized_int& other) {
        std::lock(mtx, other.mtx);
        std::lock_guard self_lock(mtx, std::adopt_lock);
        std::lock_guard other_lock(other.mtx, std::adopt_lock);
        value = other.value;
        return *this;
      }
    };
    

提交回复
热议问题