@Monsieur: You're wrong. A mutex would be useless if it couldn't maintain a
queue of waiting processes. A binary semaphore is equivalent to a mutex only
under very restricted use cases. See the mail below for details.
@Dumanshu: No. In fact I mean to say the exact opposite. A binary semaphore
is the same as a mutex under a very restricted set of circumstances.
Mutex:
void f() {
mutex_lock(&mutex1);
// Crit. Sec.
mutex_unlock(&mutex1);
}
Can be implemented using a semaphore as:
void f() {
sem_wait(&sem1);
// CS
sem_post(&sem1);
}
Semaphore:
void f() {
while(1) {
sem_wait(&sem1);
// CS1
sem_post(&sem2);
}
}
void g() {
while(1) {
sem_wait(&sem2);
// CS2
sem_post(&sem1);
}
}
If there are multiple threads accessing functions f() and g():
Given starting values of 1 and 0 to the 2 semaphores, the second
example guarantees CS executions in the order CS1, CS2, CS1, CS2...
This kind of a scenario cannot be implemented via a mutex* because
the thread that locked the semaphore is not the one that is unlocking
the semaphore. (That is - the *Owner* concept is missing).
* addendum: it might be possible but it certainly won't be obvious or easy.
A simple modification to g() like:
void g() {
while(1) {
sem_wait(&sem2);
// CS2
sem_post(&sem1);
sem_post(&sem1); // extra post
}
}
Allows for violation of mutual exclusion of both CS1 and CS2. This is
possible
given a counting semaphore but is disallowed for a mutex because
"MUTUAL EXCLUSION" is a different goal than a simple signalling
mechanism.
To reiterate: A semaphore is a signalling mechanism for cooperating
processes.
A mutex can be implemented using a semaphore. However, the goal of a mutex
is mutual exclusion in a CS. The semaphore does not have an owner concept.
The mutex does have an owner concept. The semaphore can be used to order
executions of critical sections, it's very difficult to do the same using a
mutex
due to the same *owner* condition.
I hope I'm making my point clear.
--
DK
http://twitter.com/divyekapoor
http://www.divye.in
--
You received this message because you are subscribed to the Google Groups
"Algorithm Geeks" group.
To view this discussion on the web visit
https://groups.google.com/d/msg/algogeeks/-/tu4rgpUzUUIJ.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/algogeeks?hl=en.