Riverbed Interview Question
Software Engineer / DevelopersA semaphore can be used for managing the use of a limited resource. Its initialized to the count of available resources. Now a mutex is a binary semaphore that takes only 2 values. To implement a semaphore using a mutex have an integer used as a semaphore initialized to some count. You increment and decrement this semaphore int every time resource is used and consumed. you have to make sure that each update on semaphore is gaurded by the mutex.
any thoughts ?
Use a mutex and a count variable encapsulated in a class. Implement a semLock function which inturn checks for the count and returns a bool status whether to lock or not. If it returns true, then call pthread_mutex_lock, else just reduce the count and let the processing continue. When the call exits the critical section, increment the count.
Does this make sense?
lock_t mutex;
sem_t sem;
sem_init(sem, 5); //lets say there are 5 instances of this resource available
//to access resource:
lock(mutex);
while(sem == 0)
wait();
//take resource
sem--;
unlock(mutex);
//to release resource
lock(mutex);
sem++;
unlock(mutex);
signal(); //wake up any thread waiting on the semaphore
class Sem_Mutex
{
public:
Sem_Mutex(maxReaders)
{
this.maxReaders = maxReaders
}
void lockRead() { semaphore++; }
void unlockRead() { semaphore--; }
void lockWrite() {
lock(mutex);
for (int i = 0; i < maxReaders(); ++i)
semaphore++;
unlock(mutex);
}
void unlockWrite() { semaphore = 0; }
int maxReaders() const { return semaphore; }
private:
int semaphore;
int maxReaders;
lock_t mutex;
};
/* If conditional variable is available to used together with mutex
*/
typedef semaphore_s {
pthread_mutex_t mx;
pthread_cond_t cv;
int ctr;
} sem_t;
void sem_init(sem_t *sem, int count) {
pthread_mutex_init(&sem->mx);
pthread_cond_init(&sem->cv);
sem->ctr=count;
}
void sem_wait(sem_t *sem) {
pthread_mutex_lock(&sem->mx);
while(sem->ctr==0) pthread_cond_wait(&sem->cv, &sem->mx);
sem->ctr--;
pthread_mutex_unlock(&sem->mx);
}
void sem_post(sem_t *sem) {
pthread_mutex_lock(&sem->mx);
if(sem->ctr++==0) pthread_cond_broadcast(&sem->cv);
pthread_mutex_unlock(&sem->mx);
}
- Anonymous February 28, 2011