std::unique_lock<Mutex>::lock
提供: cppreference.com
< cpp | thread | unique lock
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
を使用します。
Run this code
#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 operationstd::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
[編集]関連項目
紐付けられているミューテックスのロックを試みます。 ミューテックスが利用可能でなければ戻ります (パブリックメンバ関数) | |
紐付けられているミューテックスのロックを解除します (パブリックメンバ関数) |