Home >Backend Development >C++ >How to Safely Move C Types Containing `std::mutex`?

How to Safely Move C Types Containing `std::mutex`?

Barbara Streisand
Barbara StreisandOriginal
2024-11-30 08:11:10870browse

How to Safely Move C   Types Containing `std::mutex`?

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:

  • Copy members can be optimized by sharing a mutex in C 14.
  • Protect other methods that modify the state of A with locking mechanisms.
  • Guard against self-swap by checking for equality prior to swapping.
  • Consider using read and write lock data members to avoid default construction in copy/move constructors.

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!

Statement:
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