named_recursive_mutex
Overview
cbeam::concurrency::named_recursive_mutex
offers cross-process recursive mutex synchronization under a single, consistent API for both Unix-like systems and Windows. Unlike Boost’s implementation on Windows (which relies on file-based interprocess locks in system-wide directories), Cbeam opts for the native Windows approach to avoid file permissions issues and to gain better performance.
Key Features
- Recursive Locking: Same thread can lock multiple times (incrementing a recursion count).
- Named Object: Use the same name across processes for cross-process coordination.
- Native Windows Mutex: On Windows, leverages
CreateMutexA
/WaitForSingleObject
/ReleaseMutex
. - Posix Shared Memory: On Unix-like systems, uses
shm_open
plus apthread_mutex_t
placed in the shared region.
Boost Comparison
In Boost, named_recursive_mutex
typically creates hidden files in system-wide directories (e.g., on Windows under C:\ProgramData\boost_interprocess
). Cbeam’s design uses native Windows mutex objects instead, which:
- Avoid file path permission issues.
- Use OS-level handles with session-scoped lifetime.
- Clean up automatically when the last referencing process ends.
On Unix-like platforms, it mimics pthread_mutex_t
in shared memory, similarly avoiding file-based constructs.
Usage
#include <cbeam/concurrency/named_recursive_mutex.hpp>
int main() {
using cbeam::concurrency::named_recursive_mutex;
named_recursive_mutex myMutex("SharedLockDemo");
{
myMutex.lock();
// critical section
myMutex.unlock();
}
return 0;
}
Implementation Details
If the named mutex does not exist, it is created in shared memory (POSIX) or as a native mutex (Windows).
On Unix-like systems
shm_open
+ pthread_mutex_t
are used for real shared memory and an actual process-sharing pthread_mutex
.
On Windows
The native HANDLE
from CreateMutexA
is stored. The named mutex is thus recognized by other processes referencing the same string name.