std::unique_lock::lock
来自cppreference.com
< cpp | thread | unique lock
该页由英文版wiki使用Google Translate机器翻译而来。
该翻译可能存在错误或用词不当。鼠标停留在文本上可以看到原版本。你可以帮助我们修正错误或改进翻译。参见说明请点击这里. |
void lock(); |
(C++11 起) | |
锁定相关联的互斥体。有效地调用mutex()->lock().
原文:
Locks the associated mutex. Effectively calls mutex()->lock().
std::system_error被抛出,如果没有相关的互斥或如果该互斥锁已经锁定.
原文:
std::system_error is thrown if there is no associated mutex or if the mutex is already locked.
目录 |
[编辑] 参数
(无)
[编辑] 返回值
(无)
[编辑] 例外
- mutex()->lock()抛出的任何异常原文:Any exceptions thrown by mutex()->lock()
- 如果没有相关的互斥体,std::system_error的错误代码std::errc::operation_not_permitted原文:If there is no associated mutex, std::system_error with an error code of std::errc::operation_not_permitted
- 如果互斥锁已被锁定,std::system_error的std::errc::resource_deadlock_would_occur的错误代码原文:If the mutex is already locked, std::system_error with an error code of std::errc::resource_deadlock_would_occur
[编辑] 示例
下面的示例使用
lock
重新获取一个互斥体的解锁.
原文:
The following example uses
lock
to re-acquire a mutex that was unlocked.
#include <mutex> #include <thread> #include <iostream> #include <vector> #include <chrono> 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(); }
Possible output:
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
[编辑] 另请参阅
试图锁定相关联的互斥量,退货,如果该互斥锁不可用 原文: tries to lock the associated mutex, returns if the mutex is not available (公共成员函数) | |
解锁相关的互斥 (公共成员函数) |