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
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;
}
};