std::mutex::unlock(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

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