std::mutex performance compared to win32 CRITICAL_SECTION

Please see my updates at the end of the answer, the situation has dramatically changed since Visual Studio 2015. The original answer is below. I made a very simple test and according to my measurements the std::mutex is around 50-70x slower than CRITICAL_SECTION. std::mutex: 18140574us CRITICAL_SECTION: 296874us Edit: After some more tests it turned out … Read more

Implementing a FIFO mutex in pthreads

You can implement a fair queuing system where each thread is added to a queue when it blocks, and the first thread on the queue always gets the resource when it becomes available. Such a “fair” ticket lock built on pthreads primitives might look like this: #include <pthread.h> typedef struct ticket_lock { pthread_cond_t cond; pthread_mutex_t … Read more

Map with concurrent access

Multiple readers, no writers is okay: https://groups.google.com/d/msg/golang-nuts/HpLWnGTp-n8/hyUYmnWJqiQJ One writer, no readers is okay. (Maps wouldn’t be much good otherwise.) Otherwise, if there is at least one writer and at least one more either writer or reader, then all readers and writers must use synchronization to access the map. A mutex works fine for this.

When is a condition variable needed, isn’t a mutex enough?

Even though you can use them in the way you describe, mutexes weren’t designed for use as a notification/synchronization mechanism. They are meant to provide mutually exclusive access to a shared resource. Using mutexes to signal a condition is awkward and I suppose would look something like this (where Thread1 is signaled by Thread2): Thread1: … Read more

C++11 equivalent to boost shared_mutex

I tried but failed to get shared_mutex into C++11. It has been proposed for a future standard. The proposal is here. Edit: A revised version (N3659) was accepted for C++14. Here is an implementation: http://howardhinnant.github.io/shared_mutex http://howardhinnant.github.io/shared_mutex.cpp

How does a mutex lock and unlock functions prevents CPU reordering?

The short answer is that the body of the pthread_mutex_lock and pthread_mutex_unlock calls will include the necessary platform-specific memory barriers which will prevent the CPU from moving memory accesses within the critical section outside of it. The instruction flow will move from the calling code into the lock and unlock functions via a call instruction, … Read more