std::lock_guard 和 std::unique_lock的区别

大部分情况下,两者的功能是一样的,不过unique_lock 比lock_guard 更灵活.
unique_lock提供了lock, unlock, try_lock等接口.
lock_guard没有多余的接口,构造函数时拿到锁,析构函数时释放锁
lock_guard 比unique_lock 要省时.

class A
{
public:
    std::mutex m;
};
A e1,e2;
...
std::unique_lock::mutex> lk1(e1.m, std::defer_lock);
std::unique_lock::mutex> lk2(e2.m, std::defer_lock);
std::lock(lk1, lk2);
std::cout << e1.id << " and " << e2.id << " got locks" << std::endl;
class A
{
public:
    std::mutex m;
};
A e1,e2;
...
std::lock(e1.m, e2.m);
std::lock_guard::mutex> lock_a(e1.m, std::adopt_lock);
std::lock_guard::mutex> lock_b(e2.m, std::adopt_lock);

1) lock_guard 同一时间锁住两个mutex, 再创建guards用来管理锁的释放工作

2)unique_lock  先创建guards, 再同时锁住两个锁

C++17已经讲lock_guard标注为 Deduction guides(since C++17)

你可能感兴趣的:(c++)