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 이후)

뮤텍스를 해제합니다. 뮤텍스는 현재 실행 스레드에 의해 잠겨 있어야 하며, 그렇지 않을 경우 동작은 정의되지 않습니다.

이 연산은 synchronizes-with (다음과 같이 정의됨 std::memory_order ) 동일한 뮤텍스의 소유권을 획득하는 후속 lock 연산과.

참고 사항

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 for mtx_unlock