Skip to content

named_mutex

Alairion edited this page May 8, 2021 · 5 revisions

nes::named_mutex

Defined in header <nes/named_mutex.hpp>

class named_mutex;

Description

nes::named_mutex is the default named mutex implementation. It can be locked and unlocked. You can try to lock it in order to prevent the calling thread from waiting if it is already owned by another thread.
It can be shared among multiple processes using its name. If a process exits (for whatever reason) without unlocking a named mutex, it is automatically unlocked by the operating system so other processes won't be deadlocked.

Member types

Type Description
native_handle_type The underlying, implementation-defined, representation of a named mutex object

Public Member functions

Function Description
named_mutex Create a new, or open an existing, named mutex object
~named_mutex Destroys the named mutex object
operator= Not assignable
lock Locks the mutex, blocks if the mutex is already locked
try_lock Locks the mutex
unlock Unlocks the mutex
native_handle Returns the underlying, implementation-defined, representation of a named mutex

Example

Here is an example in which we can see cross-process mutex locking.
main.cpp is the main file of the parent process.
other.cpp is the main file of the child process.
Possible output is the standard output of the parent process.

main.cpp

#include <mutex>
#include <thread>

#include <nes/named_mutex.hpp>
#include <nes/process.hpp>

int main()
{
    //Create a new named mutex
    nes::named_mutex mutex{"nes_example_named_mutex"};
    //Acquire ownership of the new mutex
    std::unique_lock lock{mutex};

    //Start the other process
    nes::process other{other_path, nes::process_options::grab_stdout};

    //Wait few time before unlocking the mutex
    std::this_thread::sleep_for(std::chrono::milliseconds{500});
    lock.unlock();

    //Read the entire standard output of the child process. (nes::process_options::grab_stdout must be specified on process creation)
    std::cout << other.stdout_stream().rdbuf() << std::endl;

    if(other.joinable())
        other.join();
}

other.cpp

#include <mutex>
#include <thread>
#include <iostream>

#include <nes/named_mutex.hpp>

int main()
{
    auto tp1 = std::chrono::high_resolution_clock::now();

    //Open the named mutex
    nes::named_mutex mutex{"nes_example_named_mutex"};
    std::lock_guard lock{mutex};

    auto tp2 = std::chrono::high_resolution_clock::now();
    std::cout << "Gained ownership of the mutex after " << std::chrono::duration_cast<std::chrono::duration<double>>(tp2 - tp1).count() << "s." << std::endl;
}

Possible output

Gained ownership of the mutex after 0.494937s.
Clone this wiki locally