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

后端 未结 2 1038
生来不讨喜
生来不讨喜 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<std::mutex> lock(other.mtx);
        value = std::move(other.value);
        other.value = 0;
      }
    
      // Copy initialization
      synchronized_int(const synchronized_int& other) {
        std::lock_guard<std::mutex> lock(other.mtx);
        value = other.value;
      }
    
      // Move assignment
      synchronized_int& operator = (synchronized_int&& other) {
        std::lock(mtx, other.mtx);
        std::lock_guard<std::mutex> self_lock(mtx, std::adopt_lock);
        std::lock_guard<std::mutex> 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<std::mutex> self_lock(mtx, std::adopt_lock);
        std::lock_guard<std::mutex> other_lock(other.mtx, std::adopt_lock);
        value = other.value;
        return *this;
      }
    };
    
    0 讨论(0)
  • 2021-02-14 20:49

    Declare your mutex dynamically and not statically.

    At your Database class header declare the mutex as a pointer, like that:

    mutex * semaphore;
    

    and at your constructor initialize the mutex calling his constructor:

    semaphore = new std::mutex();
    
    0 讨论(0)
提交回复
热议问题