Download presentation
Presentation is loading. Please wait.
Published byBartholomew Greer Modified over 9 years ago
1
Condition Variables Condition variables support three operations: Wait – add calling thread to the condition variable’s queue and put the thread to sleep Signal – remove a thread, if any, from the condition variable’s queue and wake it up Broadcast – remove and wake-up all threads in the condition variables queue
2
Typical Use Mutex mx; GetLock (condition cv, mutex mx) { mutex_acquire (mx); while (LOCKED) wait (cv,mx) ; lock=LOCKED; mutex_release (mx); }
3
Typical Use (cont.) ReleaseLock (condition cv, mutex mx) { mutex_acquire (mx); lock = UNLOCKED; signal (cv); mutex_release (mx); }
4
CV Implementation – Data Struct. struct condition { proc next; /* doubly linked list implementation of */ proc prev; /* queue for blocked threads */ mutex listLock; /*protects queue */ };
5
CV – Wait Implementation void wait (condition *cv, mutex *mx) { mutex_acquire(&cv->listLock); /* protect the queue */ enqueue(&cv->next, &cv->prev, thr_self()); /* enqueue */ mutex_release (&cv->listLock); /* we're done with the list */ /* The suspend and mutex_release operation must be atomic */ mutex_release(mx); thr_suspend (self); /* Sleep 'til someone wakes us */ mutex_acquire(mx); /* Woke up – our turn, get resource lock */ return; }
6
CV – Signal Implementation void signal (condition *cv) { thread_id tid; mutex_acquire(cv->listlock); /* protect the queue */ tid = dequeue(&cv->next, &c->prev); mutex_release(listLock); if (tid>0) thr_continue (tid); return; } /* Note: This did not release mx */
7
CV Implementation - Broadcast void broadcast (condition *cv) { thread_id tid; mutex_acquire(c->listLock); /* protect the queue */ while (&cv->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 */ } /* Note: This did not release mx */
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.