Assignment via copy-and-swap vs two locks

后端 未结 1 1612
刺人心
刺人心 2021-01-12 20:08

Borrowing Howard Hinnant\'s example and modifying it to use copy-and-swap, is this op= thread-safe?

struct A {
  A() = default;
  A(A const &x);  // Assu         


        
1条回答
  •  借酒劲吻你
    2021-01-12 20:31

    I believe your assignment is thread safe (assuming of course no references outside the class). The performance of it relative to the const A& variant probably depends on A. I think for many A that your rewrite will be just as fast if not faster. The big counter-example I have is std::vector (and classes like it).

    std::vector has a capacity that does not participate in its value. And if the lhs has sufficient capacity relative to the rhs, then reusing that capacity, instead of throwing it away to a temp, can be a performance win.

    For example:

    std::vector v1(5);
    std::vector v2(4);
    ...
    v1 = v2;
    

    In the above example, if v1 keeps its capacity to do the assignment, then the assignment can be done with no heap allocation or deallocation. But if vector uses the swap idiom, then it does one allocation and one deallocation.

    I note that as far as thread safety goes, both algorithms lock/unlock two locks. Though the swap variant avoids the need to lock both of them at the same time. I believe on average the cost to lock both at the same time is small. But in heavily contested use cases it could become a concern.

    0 讨论(0)
提交回复
热议问题