std::mutex:: unlock
From cppreference.net
C++
Concurrency support library
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
std::mutex
| Member functions | ||||
| Locking | ||||
|
mutex::unlock
|
||||
| Native handle | ||||
|
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
参见
|
锁定互斥锁,若互斥锁不可用则阻塞
(公开成员函数) |
|
|
尝试锁定互斥锁,若互斥锁不可用则立即返回
(公开成员函数) |
|
|
C 文档
for
mtx_unlock
|
|