std::unique_lock<Mutex>::lock
来自 cppreference.com
< cpp | thread | unique lock
void lock(); |
(自 C++11 起) | |
锁定(即,获取相关互斥锁的所有权)。实际上调用 mutex()->lock().
内容 |
[编辑] 参数
(无)
[编辑] 返回值
(无)
[编辑] 异常
- mutex()->lock() 抛出的任何异常。
- 如果没有关联的互斥锁,则抛出 std::system_error,其错误代码为 std::errc::operation_not_permitted.
- 如果互斥锁已被此
unique_lock
锁定(换句话说,owns_lock() 为 true),则抛出 std::system_error,其错误代码为 std::errc::resource_deadlock_would_occur.
[编辑] 示例
以下示例使用 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 << ", initial counter: " << counter << '\n'; lock.unlock(); // don't hold the lock while we simulate an expensive operation std::this_thread::sleep_for(std::chrono::seconds(1)); lock.lock(); ++counter; std::cout << id << ", final counter: " << counter << '\n'; }; for (int i = 0; i < 10; ++i) threads.emplace_back(worker_task, i); for (auto& thread : threads) thread.join(); }
可能的输出
0, initial counter: 1 1, initial counter: 2 2, initial counter: 3 3, initial counter: 4 4, initial counter: 5 5, initial counter: 6 6, initial counter: 7 7, initial counter: 8 8, initial counter: 9 9, initial counter: 10 6, final counter: 11 3, final counter: 12 4, final counter: 13 2, final counter: 14 5, final counter: 15 0, final counter: 16 1, final counter: 17 7, final counter: 18 9, final counter: 19 8, final counter: 20
[编辑] 另请参阅
尝试锁定(即,获取相关互斥锁的所有权)而不阻塞 (公共成员函数) | |
解锁(即,释放相关互斥锁的所有权) (公共成员函数) |