Handling Mutexes in Movable C Types
Overview:
In C , move semantics enhance efficiency by allowing types to be moved efficiently without copying. However, the standard mutex (std::mutex) is neither movable nor copyable, posing a challenge for implementing move-enabled types that leverage mutexes.
Problem:
How can a class (A) containing a mutex be made movable in a thread-safe manner?
Solution:
To enable moveability, define lock types (ReadLock and WriteLock) as aliases for shared or unique locks. Utilize these types to protect member accesses within move-related operations.
Move Constructor:
A(A&& a) { WriteLock rhs_lk(a.mut_); field1_ = std::move(a.field1_); 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_); field1_ = a.field1_; 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 to Safely Move C Types Containing `std::mutex`?. For more information, please follow other related articles on the PHP Chinese website!