adopt-创新互联
c++ 中lock_guard
通过 raii 机制实现了自动上锁和解锁互斥量,基本用法为
{static std::mutex io_mutex;
std::lock_guardlk(io_mutex);
std::cout<< "ddd"<< std::endl;
}
如果一段代码同时需要锁住两个互斥量, 不正确使用可能会引起死锁,比如再下面的代码中,先创建了两个unique_lock
,defer_lock
表示创建的时候不申请锁,后面人为的进行上锁
❯ cat defer_lock.cpp
#include#include#includeusing namespace std;
std::mutex mtx1, mtx2;
void f1(){{ // 因为后面要调用 lock 方法,所以使用 unique_lock 而不是 lock_guard
std::unique_locklk1(mtx1, std::defer_lock); // 1 创建 lk1的时候不去上锁
std::unique_locklk2(mtx2, std::defer_lock);// 2
lk1.lock(); // 3 不能使用 lock(lk1), 它的参数至少要两个
lk2.lock(); // 4 Risk of deadlock !
std::cout<< "ddd"<< endl;
// ...
}
}
int main(){thread t1(f1);
thread t2(f1);
t1.join();
t2.join();
}
如果两个 lock 分开执行,而且有两个线程,一个先执行了lk1.lock()
,另一个线程先执行了lk2.lock()
,那么将会出现死锁
解决方法是对两个互斥量同时上锁
❯ cat defer_lock.cpp
#include#include#includeusing namespace std;
std::mutex mtx1, mtx2;
void f1(){{ std::unique_locklk1(mtx1, std::defer_lock); // 1
std::unique_locklk2(mtx2, std::defer_lock); // 2
lock(lk1, lk2); // 3 同时上锁
std::cout<< "ddd"<< endl;
// ...
}
}
int main(){thread t1(f1);
thread t2(f1);
t1.join();
t2.join();
}
或者先同时上锁,再创建 guard,adopt_lock 要求调用线程当前拥有锁
std::lock(mtx1, mtx2);
std::lock_guardlock_a(mtx1, std::adopt_lock);
std::lock_guardlock_b(mtx2, std::adopt_lock);
在 c++17 中引入了scoped_lock
, 它上面两种方法是等价的
下面的三种方法是等价的
{// use std::scoped_lock to acquire two locks without worrying about
// other calls to assign_lunch_partner deadlocking us
// and it also provides a convenient RAII-style mechanism
std::scoped_lock lock(e1.m, e2.m);
// Equivalent code 1 (using std::lock and std::lock_guard)
// std::lock(e1.m, e2.m);
// std::lock_guardlk1(e1.m, std::adopt_lock);
// std::lock_guardlk2(e2.m, std::adopt_lock);
// Equivalent code 2 (if unique_locks are needed, e.g. for condition variables)
// std::unique_locklk1(e1.m, std::defer_lock);
// std::unique_locklk2(e2.m, std::defer_lock);
// std::lock(lk1, lk2);
}
总结下面三种方法在同时锁住多个互斥量时,是等价的
- 先同时 lock,再创建 guard
- 先创建 guard, 再同时 lock
- 使用 scoped_lock
Type | Effect(s) |
---|---|
defer_lock_t | do not acquire ownership of the mutex |
try_to_lock_t | try to acquire ownership of the mutex without blocking |
adopt_lock_t | assume the calling thread already has ownership of the mutex |
- c++ - What’s the difference between first locking and creating a lock_guard(adopt_lock) and creating a unique_lock(defer_lock) and locking? - Stack Overflow
- std::scoped_lock - cppreference.com
- c++ 并发编程实战
你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧
当前名称:adopt-创新互联
网站网址:http://ybzwz.com/article/cdigpj.html