std::unique_lock<Mutex>::lock
来自cppreference.com
<tbody>
</tbody>
void lock(); |
(C++11 起) | |
锁定关联互斥体(即获取其所有权)。相当于调用 mutex()->lock()。
参数
(无)
返回值
(无)
异常
mutex()->lock()所抛的任何异常。
- 若无关联互斥体,则为以 std::errc::operation_not_permitted 为错误码的 std::system_error。
- 若关联互斥体已为此
unique_lock所锁定(换言之,owns_lock() 为true),则为以 std::errc::resource_deadlock_would_occur 为错误码的 std::system_error。
示例
下列示例用 lock 重获得被解锁的互斥体。
运行此代码
#include <chrono>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
int main()
{
int counter = 0;
std::mutex counter_mutex;
std::vector<std::thread> threads;
auto worker_task = [&](int id)
{
std::unique_lock<std::mutex> lock(counter_mutex);
++counter;
std::cout << id << ", 内部计数器: " << counter << '\n';
lock.unlock();
// 我们模拟昂贵操作时不保有锁
std::this_thread::sleep_for(std::chrono::seconds(1));
lock.lock();
++counter;
std::cout << id << ", 最终计数器: " << counter << '\n';
};
for (int i = 0; i < 10; ++i)
threads.emplace_back(worker_task, i);
for (auto &thread : threads)
thread.join();
}
可能的输出:
0, 内部计数器: 1
1, 内部计数器: 2
2, 内部计数器: 3
3, 内部计数器: 4
4, 内部计数器: 5
5, 内部计数器: 6
6, 内部计数器: 7
7, 内部计数器: 8
8, 内部计数器: 9
9, 内部计数器: 10
6, 最终计数器: 11
3, 最终计数器: 12
4, 最终计数器: 13
2, 最终计数器: 14
5, 最终计数器: 15
0, 最终计数器: 16
1, 最终计数器: 17
7, 最终计数器: 18
9, 最终计数器: 19
8, 最终计数器: 20
参阅
| 尝试锁定(即获得其所有权)关联互斥体而不阻塞 (公开成员函数) | |
| 解锁(即释放其所有权)关联互斥体 (公开成员函数) |