Namespaces
Variants

std::mutex:: unlock

From cppreference.net

Concurrency support library
Threads
(C++11)
(C++20)
this_thread namespace
(C++11)
(C++11)
Cooperative cancellation
Mutual exclusion
Generic lock management
Condition variables
(C++11)
Semaphores
Latches and Barriers
(C++20)
(C++20)
Futures
(C++11)
(C++11)
(C++11)
Safe reclamation
Hazard pointers
Atomic types
(C++11)
(C++20)
Initialization of atomic types
(C++11) (deprecated in C++20)
(C++11) (deprecated in C++20)
Memory ordering
(C++11) (deprecated in C++26)
Free functions for atomic operations
Free functions for atomic flags
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