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

Why doesn’t Mutex get released when disposed?

The documentation explains (in the “Remarks” section) that there is a conceptual difference between instantiating a Mutex object (which does not, in fact, do anything special as far as synchronization goes) and acquiring a Mutex (using WaitOne). Note that: WaitOne returns a boolean, meaning that acquiring a Mutex can fail (timeout) and both cases must … Read more

System-wide mutex in Python on Linux

The “traditional” Unix answer is to use file locks. You can use lockf(3) to lock sections of a file so that other processes can’t edit it; a very common abuse is to use this as a mutex between processes. The python equivalent is fcntl.lockf. Traditionally you write the PID of the locking process into the … Read more

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