Home >Backend Development >C++ >How Can I Make My C Class with a Mutex Movable and Thread-Safe?
Handling Mutexes in Movable Types in C
Issue:
Due to the non-copyable and non-movable nature of std::mutex, classes holding mutexes lack default move constructors, making it challenging to create movable thread-safe types.
Solution:
To achieve thread-safe move semantics for class A holding a mutex, adopt the following strategies:
Move Constructor:
A(A&& a) { WriteLock rhs_lk(a.mut_); // Lock the rhs mutex field1_ = std::move(a.field1_); // Move the data field2_ = std::move(a.field2_); }
Move Assignment Operator:
A& operator=(A&& a) { if (this != &a) { WriteLock lhs_lk(mut_, std::defer_lock); WriteLock rhs_lk(a.mut_, std::defer_lock); std::lock(lhs_lk, rhs_lk); field1_ = std::move(a.field1_); field2_ = std::move(a.field2_); } return *this; }
Copy Constructor:
A(const A& a) { ReadLock rhs_lk(a.mut_); // Lock the rhs mutex for reading field1_ = a.field1_; // Copy the data field2_ = a.field2_; }
Copy Assignment Operator:
A& operator=(const A& a) { if (this != &a) { WriteLock lhs_lk(mut_, std::defer_lock); ReadLock rhs_lk(a.mut_, std::defer_lock); std::lock(lhs_lk, rhs_lk); field1_ = a.field1_; field2_ = a.field2_; } return *this; }
Other Considerations:
The above is the detailed content of How Can I Make My C Class with a Mutex Movable and Thread-Safe?. For more information, please follow other related articles on the PHP Chinese website!