Difference Between Mutex and Binary Semaphore in progrmming
So Guys first we have to know that what is mutex and binary semaphore............
Mutex ...............
if you extract this word you got two different words "Bhaichara" ha.....ha...... means
mutual exclusion, i think you got some idea about Mutex
Mutex is generally used in multithreaded programming, where two or more threads fight together to
access part of code or variable at a same time in it's critical section.
So for creating peace between two or more "DAEMON" like thread which fight to eat whole things at a same time we have a solution called "mutex".
but we need to go more tch..
so, Mutex control access to shared single resources between two or more thread.
Explanation:---
Lets thread T1 , T2 , and T3 try to access a critical section.
For that we have mutex_lock or mutex_unlock.....
Now what T1 do before going to critical section, it locks the mutex by using mutex_lock...means door closed no any thread can access critical section that time because they are not
Rajnikant but whenever T1 unlock the mutex by using mutex_unlock then T2 or T3 can get access to critical section and lock the mutex. Untill it finished it works in lock room "dirty mind" int it's critical section..............
before going to binary semaphore i want to explain Semaphore...........
A semaphore control access to shared a pool of resources, basically it is a integer variable which may be greater than 1.
For example we have a semaphore variable with
int i=4; then we can give mutex _lock to more than one thread at a same time untill i becomes to 0.
Now question arises can one thread have more than one lock and answer is big YES. According to your code or logic a thread may have more than one lock.
Now come to the main point
Binary Semaphore
Binary Semaphore: - It is also a integer variable like semaphore but with only 0 or 1 values and when you are trying to explain it , you get confused between mutex and semaphore because both seems to be same but actually it is not.
Let's feel it ...........
In Binary semaphore when one thread try to access critical section it set the value of int i to 0 and untill it finished the work no any thread can access it and after accessing the critical section it again set to int i=1 and continue..................
it same as mutex but here is one difference mutex has ownership means thread which acquire the lock only that thread can free it but in binary semaphore other thread can also free it and get access to critical section
you can say that
A mutex is semaphore but a semaphore never be a mutex..................