std::mutex::unlock
來自 cppreference.com
void unlock(); |
(C++11 起) | |
解鎖互斥體。
互斥體必須由當前執行執行緒鎖定,否則行為未定義。
此操作與任何後續獲取相同互斥體所有權的鎖定操作進行同步-與(定義見std::memory_order)。
目錄 |
[編輯] 引數
(無)
[編輯] 返回值
(無)
[編輯] 異常
不丟擲任何異常。
[編輯] 註記
unlock()
通常不直接呼叫:std::unique_lock 和 std::lock_guard 用於管理獨佔鎖定。
[編輯] 示例
此示例展示瞭如何使用 lock
和 unlock
來保護共享資料。
執行此程式碼
#include <chrono> #include <iostream> #include <mutex> #include <thread> int g_num = 0; // protected by g_num_mutex std::mutex g_num_mutex; void slow_increment(int id) { for (int i = 0; i < 3; ++i) { g_num_mutex.lock(); int g_num_running = ++g_num; g_num_mutex.unlock(); std::cout << id << " => " << g_num_running << '\n'; std::this_thread::sleep_for(std::chrono::seconds(1)); } } int main() { std::thread t1(slow_increment, 0); std::thread t2(slow_increment, 1); t1.join(); t2.join(); }
可能的輸出
0 => 1 1 => 2 0 => 3 1 => 4 0 => 5 1 => 6
[編輯] 另見
鎖定互斥體,如果互斥體不可用則阻塞 (public member function) | |
嘗試鎖定互斥體,如果互斥體不可用則返回 (public member function) | |
C 文件 for mtx_unlock
|