#include <mutex>
using namespace std;
class Dummy {};
void swap(Dummy& lhs,Dummy& rhs);
class A
{
private:
Dummy myObj;
std::mutex mu;
public:
A(Dummy const& obj):myObj(obj){}
friend void swap(A& lhs, A& rhs)
{
// the arguments are checked to ensure they are different instances,
// because attempting to acquire a lock on a std::mutex
// when we already hold it is undefined behavior.
if(&lhs==&rhs) return;
// the call to std::lock() locks the two mutexes
std::lock(lhs.mu,rhs.mu);
// two std::lock_guard instances are constructed one for each mutex.
std::lock_guard<std::mutex> lock_a(lhs.mu,std::adopt_lock);
std::lock_guard<std::mutex> lock_b(rhs.mu,std::adopt_lock);
swap(lhs.myObj, rhs.myObj);
}
}; swap函数开始会检测参数是否相同,因为重复去lock一个已经被锁定了的std::mutex会导致未知行为。如果需要支持重复的lock, 可以采用std::recursive_mutex。C++11线程指南(七)--死锁,布布扣,bubuko.com
原文地址:http://blog.csdn.net/shltsh/article/details/38457337