Lecture 5: Synchronization: Too Much Milk 5.0 Motivation
Lecture 5: Synchronization: Too Much Milk 5.0 Motivation
5.0 Motivation
Person A Person B
3:00 Look in fridge. Out of milk.
3:05 Leave for store.
3:10 Arrive at store. Look in fridge. Out of milk.
3:15 Buy milk. Leave for store.
3:20 Arrive home, put milk away. Arrive at store.
3:25 Buy milk.
3:30 Arrive home, put milk away.
Oh no!
5.1 Definitions
What are the correctness properties for the too much milk
problem?
never more than one person buys
someone buys if needed
Solution #1:
if (noMilk) {
if (noNote){
leave Note;
buy milk;
remove note;
}
}
Why doesn't this work? Thread can get context switched after
checking milk and note, but before buying milk!
Solution #2:
Thread A Thread B
leave note A leave note B
if (noNote B){ if (noNoteA){
if (noMilk) if (noMilk)
buy milk buy milk
} }
remove note A remove note B
Solution #3:
Thread A Thread B
leave note A leave note B
while (note B)// X if (noNoteA){// Y
do nothing; if if (noMilk)
(noMilk) buy milk
buy milk; }
remove note A remove note B
With locks, the too much milk problem becomes really easy!
lock->Acquire();
if (nomilk)
buy milk;
lock->Release();