user152949
user152949

Reputation:

Are there C++11 critical sections?

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.

Upvotes: 5

Views: 8446

Answers (3)

G Hx
G Hx

Reputation: 1147

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"
  }

Upvotes: 0

James Kanze
James Kanze

Reputation: 153909

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 mmaped space, which is accessible from several processes.

Upvotes: 1

Casey
Casey

Reputation: 42554

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.

Upvotes: 9

Related Questions