You are on page 1of 8

Too Much Milk

Person A
3:00 Arrive home: no milk
3:05 Leave for store
3:10 Arrive at store
3:15 Leave store
3:20 Arrive home, put milk away

CS 140 Lecture Notes: Concurrency Slide 1


Too Much Milk
Person A Person B
3:00 Arrive home: no milk
3:05 Leave for store
3:10 Arrive at store Arrive home: no milk
3:15 Leave store Leave for store
3:20 Arrive home, put milk away Arrive at store
3:25 Leave store
3:30 Arrive home: too much milk!

CS 140 Lecture Notes: Concurrency Slide 2


Computerized Milk Purchase

if (!GotMilk) {
if (NoNote) {
Leave Note;
Buy Milk;
Remove Note;
}
}

CS 140 Lecture Notes: Concurrency Slide 3


Still Too Much Milk
Thread A: Thread B:
if (!GotMilk) {
if (NoNote) {
if (!GotMilk) {
if (NoNote) { Leave Note;
Buy Milk;
Remove Note;
}
}
Leave Note;
Buy Milk;
Remove Note;
}
}
CS 140 Lecture Notes: Concurrency Slide 4
Second Attempt

Thread A: Thread B:

if (NoNote) { if (Note) {
if (!GotMilk) { if (!GotMilk) {
Buy Milk; Buy Milk;
} }
Leave Note; Remove Note;
} }

CS 140 Lecture Notes: Concurrency Slide 5


Third Attempt

Thread A: Thread B:

1 Leave NoteA; 1 Leave NoteB;


2 if (No NoteB) { 2 if (No NoteA) {
3 if (!GotMilk) { 3 if (!GotMilk) {
4 Buy Milk; 4 Buy Milk;
5 } 5 }
6 } 6 }
7 Remove NoteA; 7 Remove NoteB;

CS 140 Lecture Notes: Concurrency Slide 6


Fourth Attempt

Thread A: Thread B:

1 Leave NoteA; 1 Leave NoteB;


2 if (No NoteB) { 2 while (NoteA) {
3 if (!GotMilk) { 3 do nothing
4 Buy Milk; 4 }
5 } 5 if (!GotMilk) {
6 } 6 Buy Milk;
7 Remove NoteA; 7 }
8 Remove NoteB;

CS 140 Lecture Notes: Concurrency Slide 7


CS 140 Lecture Notes: Concurrency Slide 8

You might also like