mutual exclusion and synchronization

The prevailing thinking is that mutual exclusion is part of thread/process synchronization mechanism.

Mutual exclusion is in fact a bit different from synchronization.

The prevailing method of mutual exclusion is to use a mutex where the same code cannot be run by two threads at the same time. Each thread has to take its turn to lock the mutex and then run the same code. The code typically is called critical section. It is very important that the critical section must refer some shared resource that should not be refer by another thread at the same time, hence the name "mutex".

Mutex is to make threads "not run the same code at the same time". Synchronization, on the other hands, allow two or more threads to run the same code at the same time. Synchronization means "at the same time". Take POSIX barrier, condvar as examples. Both literally block potentially several threads at possibly the same code point, and unblock all of them at the same time, Thus those threads' operation are "synchronized" to the "same time", and possibly at the "same code point".

As such, mutex (and its variations, e.g., rwlock, spinlock) and condvar ( and its variation, e.g., barriers, semaphore ) have quite different implication to the code.

1. waiting on a condvar for a long time is typically a normal condition, whereas waiting for a mutex for a long time for sure suggest either a bad design ( too many threads competing for the mutex ) , or an bug somewhere in the critical section ( critical section needs to be as short as possible )

2. "thunder herd" and "lock convey" and "mutex revival" are problems that are almost exclusive for mutex.

3. deadlock and starvation are exclusive for mutex too. canvar can never lead to deadlock. And starvation is not applicable to condvar either.

4. priority inversion is not applicable to condvar ( the mutex associated with the condvar is a different scenario. condvar itself cannot lead to priority inversion )

In summary, synchronization is preemptive scheduling friendly since it cannot lead to deadlock and priority inversion. Mutex is not preemptive scheduling friendly. Both are cooperative scheduling friendly where all therads/processes run at the same priority and scheduling depends either on round robin, or depends on each threads voluntarily release CPU