std::mutex::unlock(3)
Okay bestie, this is the std::mutex::unlock(3) page from the C++ Standard Libary manual β title and manual name folded in near the top, cute and accounted for π.
π NAME π
std::mutex::unlock - std::mutex::unlock
Yes, that's the whole NAME section: the thing is the thing. It's giving "I said what I said" π .
β¨ Synopsis β¨
void unlock(); (since C++11)
Unlocks the mutex. π
The mutex must be locked by the current thread of execution. If it isn't? The behavior is undefined, and we do not play with undefined behavior, periodt. π
This operation synchronizes-with (as defined in std::memory_order) any subsequent lock operation that obtains ownership of the same mutex. That's the handshake vibe β¨.
πΈ Parameters πΈ
(none) β zero, nada, not a single parameter to be found π«Ά.
π Return value π
(none) β it returns nothing, because the unlock is the moment, not the receipt π
.
π¦ Exceptions π¦
Throws nothing. Not even a little drama. π¦
π Notes π
unlock() is usually not called directly: std::unique_lock and std::lock_guard are used to manage exclusive locking. So the usual manager besties handle that for you π.
π₯ Example π₯
This example shows how lock and unlock can be used to protect shared data.
The original page has a // Run this code marker, and the code is exactly this:
#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();
}
Possible output:
0 => 1
1 => 2
0 => 3
1 => 4
0 => 5
1 => 6
π See also π
lockβ locks the mutex, blocks if the mutex is not available (public member function)try_lockβ tries to lock the mutex, returns if the mutex is not available (public member function)C documentation for mtx_unlockβ C documentation formtx_unlock
Source/version/date sign-off, because the footer deserves a moment too: http://cppreference.com, 2024.06.10, page std::mutex::unlock(3) β mwah, bye bestie π«Άπ
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms