Mutex lock threads

What you need to do is to call pthread_mutex_lock to secure a mutex, like this: pthread_mutex_lock(&mutex); Once you do this, any other calls to pthread_mutex_lock(mutex) will not return until you call pthread_mutex_unlock in this thread. So if you try to call pthread_create, you will be able to create a new thread, and that thread will … Read more

Is it possible to use mutex in multiprocessing case on Linux/UNIX ?

Mutual exclusion locks (mutexes) prevent multiple threads from simultaneously executing critical sections of code that access shared data (that is, mutexes are used to serialize the execution of threads). All mutexes must be global. A successful call for a mutex lock by way of mutex_lock() will cause another thread that is also trying to lock … Read more

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

How do mutexes really work?

Low-level atomic operations. These are essentially mutexes implemented in hardware, except you can only perform a very few operations atomically. Consider the following equivalent pseudocode: mutex global_mutex; void InterlockedAdd(int& dest, int value) { scoped_lock lock(mutex); dest += value; } int InterlockedRead(int& src) { scoped_lock lock(mutex); return src; } void InterlockedWrite(int& dest, int value) { scoped_lock … Read more

How to give priority to privileged thread in mutex locking?

I can think of three methods using only threading primitives: Triple mutex Three mutexes would work here: data mutex (‘M’) next-to-access mutex (‘N’), and low-priority access mutex (‘L’) Access patterns are: Low-priority threads: lock L, lock N, lock M, unlock N, { do stuff }, unlock M, unlock L High-priority thread: lock N, lock M, … Read more

Object synchronization method was called from an unsynchronized block of code. Exception on Mutex.Release()

Keeping a bool around that indicates that the mutex is owned is a grave mistake. You are not making the bool thread-safe. You got into this pickle because you are using the wrong synchronization object. A mutex has thread-affinity, the owner of a mutex is a thread. The thread that acquired it must also be … Read more

Use std::lock_guard with try_lock

A basic design invariant of lock_guard is that it always holds the lock. This minimizes the overhead since its destructor can unconditionally call unlock(), and it doesn’t have to store extra state. If you need the try-to-lock behavior, use unique_lock: std::unique_lock<std::mutex> lock(_mutex, std::try_to_lock); if(!lock.owns_lock()){ // mutex wasn’t locked. Handle it. }