std:: defer_lock, std:: try_to_lock, std:: adopt_lock, std:: defer_lock_t, std:: try_to_lock_t, std:: adopt_lock_t
From cppreference.net
C++
Concurrency support library
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
定义于头文件
<mutex>
|
||
|
struct
defer_lock_t
{
explicit
defer_lock_t
(
)
=
default
;
}
;
|
(1) | (C++11 起) |
|
constexpr
std::
defer_lock_t
defer_lock
{
}
;
|
(2) |
(C++11 起)
(C++17 起为内联) |
|
struct
try_to_lock_t
{
explicit
try_to_lock_t
(
)
=
default
;
}
;
|
(3) | (C++11 起) |
|
constexpr
std::
try_to_lock_t
try_to_lock
{
}
;
|
(4) |
(C++11 起)
(C++17 起为内联) |
|
struct
adopt_lock_t
{
explicit
adopt_lock_t
(
)
=
default
;
}
;
|
(5) | (C++11 起) |
|
constexpr
std::
adopt_lock_t
adopt_lock
{
}
;
|
(6) |
(C++11 起)
(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) // 避免自转账时的死锁 return; // 无死锁地锁定两个互斥量 std::lock(from.m, to.m); // 确保两个已锁定的互斥量在作用域结束时被解锁 std::lock_guard lock1{from.m, std::adopt_lock}; std::lock_guard 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>
的公开成员函数)
|