Skip to content

timed_named_mutex

Alairion edited this page May 8, 2021 · 5 revisions

nes::timed_named_mutex

Defined in header <nes/named_mutex.hpp>

class timed_named_mutex;

Description

nes::timed_named_mutex is a named mutex implementation that provides time-based locking. It can be locked and unlocked, with or without timeout. 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
timed_named_mutex Creates a new, or opens an existing, named mutex object
~timed_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
try_lock_for Tries to lock the mutex for a specified time
try_lock_until Tries to lock the mutex until a specified time point is reached
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 <nes/named_mutex.hpp>
#include <nes/process.hpp>

int main()
{
    //Create a new timed named mutex
    nes::timed_named_mutex mutex{"nes_example_timed_named_mutex"};
    //Lock it
    std::unique_lock lock{mutex};

    //Create a subprocess that also use that mutex
    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{1000});
    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 <iostream>

#include <nes/named_mutex.hpp>

int main()
{
    //Open the mutex
    nes::timed_named_mutex mutex{"nes_example_timed_named_mutex"};
    std::unique_lock lock{mutex, std::defer_lock};

    //Try to lock the mutex with small timeout so we don't block the thread
    std::uint32_t tries{};
    while(!lock.try_lock_for(std::chrono::milliseconds{10}))
        ++tries;

    std::cout << "Gained ownership of the mutex after " << tries << " tries." << std::endl;
}

Possible output

Gained ownership of the mutex after 99 tries.
Clone this wiki locally