I'm working with mutex and when building the code, its throwing an error: 'error: use of deleted function 'std::mutex::mutex(const std::mutex&)'
I understand why I'm getting this error, referred to this answer: Attempting to reference a deleted function when using a mutex . Now, I don't know how can I actually acquire the mutex stored in the instance being copied. Any general example would help. Thanks!
EDIT
file.h
class A
{
...
std::mutex taskMutex;
bool isExecuting;
...
}
file.cpp
int function1
{
std::unique_lock<std::mutex> lock(taskMutex);
...
( lambda func executing )
isExecuting = true
...
isExecuting = false
}
int function2
{
while(isExecuting);
std::unique_lock<std::mutex> lock(taskMutex);
}
Since each instance should be lockable, you need to lock the object while copying from it - which also may cause problems if it has non-default constructible member variables.
One idea could be to add a unique_lock
member that can lock the object being copied or moved from while doing the copying/moving.
Here's an outline:
class Foo {
public:
Foo() = default;
Foo(const Foo& rhs) : // copy constructor
ul(rhs.mtx), // lock the object being copied from
member(rhs.member) // copy its members in the member initializer list
{
ul.unlock(); // unlock
}
Foo(Foo&& rhs) noexcept : // move constructor
ul(rhs.mtx), // lock the object being moved from
member(std::move(rhs.member)) // move its members in the member init-list
{
ul.unlock(); // unlock
}
Foo& operator=(const Foo& rhs) { // copy assignment
std::scoped_lock lock(mtx, rhs.mtx); // lock both objects involved
member = rhs.member; // ... and copy
return *this;
}
Foo& operator=(Foo&& rhs) noexcept { // move assignment
std::scoped_lock lock(mtx, rhs.mtx); // lock both objects involved
member = std::move(rhs.member); // ... and move
return *this;
}
private:
std::unique_lock<std::mutex> ul; // used to lock rhs while copy/move constructing
mutable std::mutex mtx;
std::string member;
};
Note that the mutex
and unique_lock
member variables are not copied or moved at any time.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.