Mutex is basically a locking mechanism where a process locks a resource using mutex. Till the time, process has mutex, no other process can have the same resource. (Mutually exclusive for you). Once process is done with resource, it releases the mutex.
Here comes the concept of ownership. Mutex is locked and released by the same process/thread. It cannot happen that mutex is acquired by one process and released by other.
Semaphore is a synchronization mechanism. It is used between two process to synchronize each other. Best example would be producer-consumer problem. Consumer cannot consume till the time producer has produced something. When producer has produced something, it will inform consumer using semaphore primitive.
There is no ownership attached to semaphore. One process can acquire it and other can release it.
http://buttercola.blogspot.com/2014/11/interview-knowledge-based-questions-1.html
A mutex is like a lock. Mutexes are used in parallel programming to ensure that only one thread can access a shared resource at a time.
a semaphore is as a record of how many units of a particular resource are available, coupled with operations to safely (i.e., without race conditions) adjust that record as units are required or become free, and, if necessary, wait until a unit of the resource becomes available. Semaphores are a useful tool in the prevention of race conditions; however, their use is by no means a guarantee that a program is free from these problems. Semaphores which allow an arbitrary resource count are called counting semaphores, while semaphores which are restricted to the values 0 and 1 (or locked/unlocked, unavailable/available) are called binary semaphores.
How to implement a mutex?
Read full article from Algorithms and Me: Mutex Vs Semaphore
Here comes the concept of ownership. Mutex is locked and released by the same process/thread. It cannot happen that mutex is acquired by one process and released by other.
Semaphore is a synchronization mechanism. It is used between two process to synchronize each other. Best example would be producer-consumer problem. Consumer cannot consume till the time producer has produced something. When producer has produced something, it will inform consumer using semaphore primitive.
There is no ownership attached to semaphore. One process can acquire it and other can release it.
http://buttercola.blogspot.com/2014/11/interview-knowledge-based-questions-1.html
A mutex is like a lock. Mutexes are used in parallel programming to ensure that only one thread can access a shared resource at a time.
How to implement a mutex?
void
acquire_lock( Lock lock1) {
while
(test_and_set(lock1));
}
int
test_and_set(
int
x) {
if
(x) {
return
1
;
}
else
{
x =
1
;
return
0
;
}
}
void
acquire_unlokc(Lock lock1) {
lock1 =
0
;
// we need it to be atomic instruction
}