Home > Backend Development > C++ > How Can I Make My C Class with a Mutex Movable and Thread-Safe?

How Can I Make My C Class with a Mutex Movable and Thread-Safe?

Susan Sarandon
Release: 2024-11-29 06:05:14
Original
668 people have browsed it

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_);
}
Copy after login

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 after login

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 after login

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;
}
Copy after login

Other Considerations:

  • Define a ReadLock and WriteLock type alias for convenience.
  • Remember to lock both mutexes using std::lock for the move assignment operator to avoid deadlock.
  • Consider using std::shared_timed_mutex in C 14 to allow for concurrent reads.
  • Protect any member functions or free functions accessing the internal state of class A using the appropriate mutex locks.
  • If necessary, add data member locks to store ReadLock and WriteLock objects to avoid default constructing members during copying.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template