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

Смотрите также

блокирует мьютекс, блокируется если мьютекс недоступен
(public member function)
пытается заблокировать мьютекс, возвращает управление если мьютекс недоступен
(public member function)
C documentation для mtx_unlock