std::unique_lock
来自cppreference.com
该页由英文版wiki使用Google Translate机器翻译而来。
该翻译可能存在错误或用词不当。鼠标停留在文本上可以看到原版本。你可以帮助我们修正错误或改进翻译。参见说明请点击这里. |
在头文件 <mutex> 中定义
|
||
template< class Mutex > class unique_lock; |
(C++11 起) | |
类unique_lock是一个通用的互斥体的所有权封装器,允许递延锁定,定时锁定,递归锁,锁的所有权转移,使用条件变量.
原文:
The class unique_lock is a general-purpose mutex ownership wrapper allowing deferred locking, timed locking, recursive locking, transfer of lock ownership, and use with condition variables.
unique_lock
类是不可复制的,但它是可动的。所提供的Mutex
的类型应执行BasicLockable
概念.原文:
The
unique_lock
class is non-copyable, but it is movable. The supplied Mutex
type shall implement the BasicLockable
concept.目录 |
[编辑] 会员类型
类型
|
Definition |
mutex_type
|
Mutex |
[编辑] 成员函数
构建了一个 unique_lock ,可以提供的互斥锁 原文: constructs a unique_lock , optionally locking the supplied mutex (公共成员函数) | |
解锁相关的互斥体,如果拥有 原文: unlocks the associated mutex, if owned (公共成员函数) | |
解锁互斥体,如果拥有另一种获得所有权 原文: unlocks the mutex, if owned, and acquires ownership of another (公共成员函数) | |
| |
locks the associated mutex (公共成员函数) | |
试图锁定相关联的互斥量,退货,如果该互斥锁不可用 原文: tries to lock the associated mutex, returns if the mutex is not available (公共成员函数) | |
来锁定相关的 TimedLockable 互斥体,互斥体的回报,如果一直无法在指定的时间持续时间原文: attempts to lock the associated TimedLockable mutex, returns if the mutex has been unavailable for the specified time duration(公共成员函数) | |
试图锁定相关的 TimedLockable 互斥的回报,如果互斥体已经不可用,直到指定的时间点已经达到 原文: tries to lock the associated TimedLockable mutex, returns if the mutex has been unavailable until specified time point has been reached (公共成员函数) | |
解锁相关的互斥 (公共成员函数) | |
| |
掉期国家与另一个std::unique_lock 原文: swaps state with another std::unique_lock (公共成员函数) | |
断开相关的未解锁的互斥 原文: disassociates the associated mutex without unlocking it (公共成员函数) | |
| |
返回一个指针,指向相关联的互斥体 原文: returns a pointer to the associated mutex (公共成员函数) | |
测试的锁是否拥有相关联的互斥 原文: tests whether the lock owns its associated mutex (公共成员函数) | |
测试的锁是否拥有相关联的互斥 原文: tests whether the lock owns its associated mutex (公共成员函数) |
[编辑] 非成员函数
专业化的std::swap unique_lock 原文: specialization of std::swap for unique_lock (函数模板) |
[编辑] 示例
#include <mutex> #include <thread> #include <chrono> struct Box { explicit Box(int num) : num_things{num} {} int num_things; std::mutex m; }; void transfer(Box &from, Box &to, int num) { // don't actually take the locks yet std::unique_lock<std::mutex> lock1(from.m, std::defer_lock); std::unique_lock<std::mutex> lock2(to.m, std::defer_lock); // lock both unique_locks without deadlock std::lock(lock1, lock2); from.num_things -= num; to.num_things += num; lock1.unlock(); lock2.unlock(); } int main() { Box acc1(100); Box acc2(50); std::thread t1(transfer, std::ref(acc1), std::ref(acc2), 10); std::thread t2(transfer, std::ref(acc2), std::ref(acc1), 5); t1.join(); t2.join(); }