Why do we need semaphore, condition variables and other constructs. I get that a thread getting blocked until a signal is better than a thread that takes mutex lock, checks for a condition which if doesn't pass, unlock and retry till the condition passes.
Other than this, is there any other benefit.
As an example, can we implement a read-write lock using only mutex...
Something as below:
int writers = 0;
int readers = 0;
mutex lock;
read_lock()
{
mutex_lock(&lock);
while(writers == 1)
{
mutex_unlock(&lock); // unlock
mutex_lock(&lock); // retry
}
readers++;
mutex_unlock(&lock);
}
read_unlock()
{
mutex_lock(&lock);
readers--;
mutex_unlock(&lock);
}
write_lock()
{
mutex_lock(&lock);
while(r>0 || w==1)
{
mutex_unlock(&lock); // unlock
mutex_lock(&lock); // retry
}
writers++;
mutex_unlock(&lock);
}
write_unlock()
{
mutex_lock(&lock);
writers--;
mutex_unlock(&lock);
}
1) Will the above implementation even work? If not, why?
2) Can I say that everything in multi-threading can be done using just mutex?