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
< cpp‎ | thread
 
 
并发支持库
线程
(C++11)
(C++20)
(C++20)
this_thread 命名空间
(C++11)
(C++11)
(C++11)
互斥
(C++11)
(C++11)  
通用锁管理
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
defer_locktry_to_lockadopt_lockdefer_lock_ttry_to_lock_tadopt_lock_t
(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)
条件变量
(C++11)
信号量
闩与屏障
(C++20)
(C++20)
未来体
(C++11)
(C++11)
(C++11)
(C++11)
安全回收
(C++26)
(C++26)
风险指针





原子类型
(C++11)
(C++20)
原子类型的初始化
(C++11)(C++20 中弃用)
(C++11)(C++20 中弃用)
内存定序
原子操作的自由函数
原子标志的自由函数
 
在标头 <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_tstd::try_to_lock_tstd::adopt_lock_t 可在 std::unique_lockstd::shared_lock 的构造函数形参列表中使用,以指定锁定策略。
2,4,6) (1,3,5) 的相应实例 std::defer_lockstd::try_to_lockstd::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> 的公开成员函数)