Operating System 161 (OS/161)- Please code in C.
Show how to implement a Conditional Variable with a Semaphore.
Note: in this case, Conditional variables are Stateless.
Condition variable can only be used with the operations wait and signal.
–The operation
x.wait();
means that the process (thread) invoking this operation is suspended until another process invokes
x.signal();
–The x.signal operation resumes exactly one suspended process on condition variable x.
This process (thread) is marked as eligible to run If no process is suspended on condition variable x, then the signal operation has no effect.
–Note that x.wait() automatically releases the lock
struct condition {
proc next; /* doubly linked list implementation of */
proc prev; /* queue for blocked threads */
mutex mx; /*protects queue */
};
wait()
void wait (condition *cv, mutex *mx)
{
mutex_acquire(&c->listLock); /* protect the queue */
enqueue (&c->next, &c->prev, thr_self()); /* enqueue */
mutex_release (&c->listLock); /* we're done with the list */
/* The suspend and release_mutex() operation should be atomic */
release_mutex (mx));
thr_suspend (self); /* Sleep 'til someone wakes us */
mutex_acquire (mx); /* Woke up -- our turn, get resource lock */
return;
}
signal()
void signal (condition *c)
{
thread_id tid;
mutex_acquire (c->listlock); /* protect the queue */
tid = dequeue(&c->next, &c->prev);
mutex_release (listLock);
if (tid>0)
thr_continue (tid);
return;
}
broadcast()
void broadcast (condition *c)
{
thread_id tid;
mutex_acquire (c->listLock); /* protect the queue */
while (&c->next) /* queue is not empty */
{
tid = dequeue(&c->next, &c->prev); /* wake one */
thr_continue (tid); /* Make it runnable */
}
mutex_release (c->listLock); /* done with the queue */
}
Operating System 161 (OS/161)- Please code in C. Show how to implement a Conditional Variable with...