在线文档教程
C++
线程支持 | Thread support

std::unique_lock::lock

性病::独特[医]锁::锁

void lock((since C++11)

锁定相关的互斥对象。有效呼叫mutex()->lock()...

参数

%280%29

返回值

%280%29

例外

  • 引发的任何异常mutex()->lock()

  • 如果没有关联的互斥,std::system_error错误代码为std::errc::operation_not_permitted

  • 如果互斥锁已被unique_lock%28,换言之,拥有[医]锁是%29,std::system_error错误代码为std::errc::resource_deadlock_would_occur

下面的示例使用lock重新获得一个未锁定的互斥体。

二次

#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( }

二次

可能的产出:

二次

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

二次

另见

try_locktries to lock the associated mutex, returns if the mutex is not available (public member function)
unlockunlocks the associated mutex (public member function)

© cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

http://en.cppreference.com/w/cpp/线程/UNIQUE[医]锁/锁