I'm trying to find the equivalent of a critical section for C++11 , is the new C++11 mutex concept process-bound (e.g. enforces mutex only on the user-space) ? Perhaps it's implementation specific since I cannot find anything specific on it. Perhaps C++11 have their own critical section classes as mutexes are cross-process, right? Please help.
A standard library implementation is free to use any mutex implementation it likes that meets the requirements and behaviors set forth in the standard. An implementation that provides cross-process locking - which the standard doesn't require - would likely be less performant than one that does not. A high-quality implementation will therefore most likely provide process-local mutexes (mutices?).
So although one could bang out a conformant implementation of C++11 mutexes using, e.g., named semaphores, one would have a hard time selling that implementation to users. To my knowledge no popular implementation exists that provides cross-process locking in std::mutex
.
CriticalSection
under Windows: this is just a Microsoft misnomer for what every one else calls a mutex.) –
Unflinching std::mutex
is likely to be cross-process on systems where it's possible with no overhead, and process-local on systems where providing cross-process locking would be more expensive. –
Ophthalmia The C++ standard only concerns single programs, thus a single process; it has nothing to say about what happens outside of the process. At least under some Posix implementations, some "mutex" are cross-process, so under them, any C++ mutex will also be cross-process. Under other systems, it probably depends on the system.
Also: implementing the mutex in user space doesn't mean that it
can't be cross-process, since user space can include shared
memory or mmap
ed space, which is accessible from several
processes.
pthread_mutexattr_getpshared
, "If the process-shared attribute is PTHREAD_PROCESS_PRIVATE, the mutex shall only be operated upon by threads created within the same process as the thread that initialized the mutex; if threads of differing processes attempt to operate on such a mutex, the behavior is undefined." So a conforming implementation could have all mutexes shared. –
Ophthalmia You can implement it like this:
static void fn()
{
static std::mutex criticalSection;
std::lock_guard<std::mutex> lockMySection(criticalSection);
// now safely in a "critical section"
}
© 2022 - 2024 — McMap. All rights reserved.