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 ( ) ;
(seit C++11)

Entsperrt das Mutex. Das Mutex muss vom aktuellen Ausführungsthread gesperrt sein, andernfalls ist das Verhalten undefiniert.

Dieser Vorgang synchronizes-with (wie definiert in std::memory_order ) jeden nachfolgenden Sperrvorgang, der den Besitz desselben Mutex erlangt.

Hinweise

unlock() wird normalerweise nicht direkt aufgerufen: std::unique_lock und std::lock_guard werden zur Verwaltung exklusiver Sperren verwendet.

Beispiel

Dieses Beispiel zeigt, wie lock und unlock verwendet werden können, um gemeinsame Daten zu schützen.

#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();
}

Mögliche Ausgabe:

0 => 1
1 => 2
0 => 3
1 => 4
0 => 5
1 => 6

Siehe auch

sperrt das Mutex, blockiert falls das Mutex nicht verfügbar ist
(öffentliche Elementfunktion)
versucht das Mutex zu sperren, kehrt zurück falls das Mutex nicht verfügbar ist
(öffentliche Elementfunktion)
C-Dokumentation für mtx_unlock