Reading various posts on SO on differences between the two (mutex and semaphore) I have come to the following conclusion please correct me if I am wrong.This is mostly related to windows. I understand that critical sections are sections in a code that need to be protected (i.e) cannot be accessed by multiple threads at the same time. Now in order to protect those critical sections Mutexes are used. These mutexes can be either algorithms or data structures. Now mutexes can generally be in two flavours (intra process and inter process) . For intra process in which no calls to the kernel for locking are made we could use Boost Thread synchronization primitives such as
Semaphore is signaling mechanism (“I am done, you can carry on” kind
of signal). For example, if you are listening songs (assume it as one
task) on your mobile and at the same time your friend called you, an
interrupt will be triggered upon which an interrupt service routine
(ISR) will signal the call processing task to wakeup.
.. Boost.Interprocess implements similar mechanisms to synchronize
threads from different processes.
A semaphore does the same as a mutex but allows x number of threads to
A semaphore is a synchronization mechanism build around an integer value. Locking a semaphore (usually called "waiting on semaphore") decreases the value unless it's 0. In that case the thread is stopped until the semaphore value is greater than 0, so it can be properly decreased. Unlocking the semaphore (usually called "posting" or "signalling") increases the value by 1, unconditionally.
Usually when creating a semaphore you need to assign it a starting value. If you set a value bigger than 1, you can have multiple threads enter code "protected" by a semaphore.
Now, a mutex is a binary synchronization primitive. Conceptually it can be compared to a semaphore with an initial value of 1. Only a single thread can enter code protected by a mutex.
I don't know the Windows world, but on Unix semaphore is a OS construct and it can be used to synchronize multiple processes. Pthread mutexes are usually used for coordinating threads within a single process, but there are tricks that allow using mutexes for inter-process synchronization (shared memory block and special ways to create a mutex).