std::defer_lock, std::try_to_lock, std::adopt_lock, std::defer_lock_t, std::try_to_lock_t, std::adopt_lock_t
来自cppreference.com
在标头 <mutex> 定义
|
||
struct defer_lock_t { explicit defer_lock_t() = default; }; |
(1) | (C++11 起) |
(2) | ||
constexpr std::defer_lock_t defer_lock {}; |
(C++11 起) (C++17 前) |
|
inline constexpr std::defer_lock_t defer_lock {}; |
(C++17 起) | |
struct try_to_lock_t { explicit try_to_lock_t() = default; }; |
(3) | (C++11 起) |
(4) | ||
constexpr std::try_to_lock_t try_to_lock {}; |
(C++11 起) (C++17 前) |
|
inline constexpr std::try_to_lock_t try_to_lock {}; |
(C++17 起) | |
struct adopt_lock_t { explicit adopt_lock_t() = default; }; |
(5) | (C++11 起) |
(6) | ||
constexpr std::adopt_lock_t adopt_lock {}; |
(C++11 起) (C++17 前) |
|
inline constexpr std::adopt_lock_t adopt_lock {}; |
(C++17 起) | |
1,3,5) 空类标签类型
std::defer_lock_t
、std::try_to_lock_t
和 std::adopt_lock_t
可在 std::unique_lock 和 std::shared_lock 的构造函数形参列表中使用,以指定锁定策略。2,4,6) (1,3,5) 的相应实例
std::defer_lock
、std::try_to_lock
和 std::adopt_lock
可以用于传递给构造函数以标明锁定策略的类型。类模板 std::lock_guard 仅有一个构造函数接受标签 std::adopt_lock
。
类型 | 效果 |
defer_lock_t
|
不获得互斥体的所有权 |
try_to_lock_t
|
尝试获得互斥体的所有权而不阻塞 |
adopt_lock_t
|
假设调用方线程已拥有互斥体的所有权 |
示例
运行此代码
#include <iostream> #include <mutex> #include <thread> struct bank_account { explicit bank_account(int balance) : balance{balance} {} int balance; std::mutex m; }; void transfer(bank_account& from, bank_account& to, int amount) { if (&from == &to) // 避免自我转账情况中的死锁 return; // 锁定两个互斥体而不死锁 std::lock(from.m, to.m); // 保证两个已锁定互斥体在作用域结尾解锁 std::lock_guard<std::mutex> lock1(from.m, std::adopt_lock); std::lock_guard<std::mutex> lock2(to.m, std::adopt_lock); // 等价方法: // std::unique_lock<std::mutex> lock1(from.m, std::defer_lock); // std::unique_lock<std::mutex> lock2(to.m, std::defer_lock); // std::lock(lock1, lock2); from.balance -= amount; to.balance += amount; } int main() { bank_account my_account(100); bank_account your_account(50); std::thread t1(transfer, std::ref(my_account), std::ref(your_account), 10); std::thread t2(transfer, std::ref(your_account), std::ref(my_account), 5); t1.join(); t2.join(); std::cout << "my_account.balance = " << my_account.balance << "\n" "your_account.balance = " << your_account.balance << '\n'; }
输出:
my_account.balance = 95 your_account.balance = 55
参阅
构造 lock_guard ,可选地锁定给定的互斥体 ( std::lock_guard<Mutex> 的公开成员函数) | |
构造 unique_lock ,可选地锁定提供的互斥体 ( std::unique_lock<Mutex> 的公开成员函数) |