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) 对应的
std::defer_lock
、std::try_to_lock
和 std::adopt_lock
的 (1,3,5) 实例可以传递给构造函数,以指示锁定策略的类型。类模板 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) // avoid deadlock in case of self transfer return; // lock both mutexes without deadlock std::lock(from.m, to.m); // make sure both already-locked mutexes are unlocked at the end of scope std::lock_guard lock1{from.m, std::adopt_lock}; std::lock_guard lock2{to.m, std::adopt_lock}; // equivalent approach: // 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> 的公共成员函数) |