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 で定義されている通り)同じミューテックスの所有権を取得する後続のロック操作と同期します。

注記

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