Download presentation
Presentation is loading. Please wait.
1
Too Much Milk With Locks
Both threads: struct lock l; ... lock_acquire(&l); if (milk == 0) { buy_milk(); } lock_release(&l); CS 140 Lecture Notes: Concurrency
2
CS 140 Lecture Notes: Locks
Producer/Consumer, v1 char buffer[SIZE]; int count = 0; int head = 0, tail = 0; struct lock l; lock_init(&l); void put(char c) { lock_acquire(&l); count++; buffer[head] = c; head++; if (head == SIZE) { head = 0; } lock_release(&l); char get() { char c; lock_acquire(&l); count--; c = buffer[tail]; tail++; if (tail == SIZE) { tail = 0; } lock_release(&l); return c; CS 140 Lecture Notes: Locks
3
CS 140 Lecture Notes: Locks
Producer/Consumer v2 char buffer[SIZE]; int count = 0; int head = 0, tail = 0; struct lock l; lock_init(&l); void put(char c) { lock_acquire(&l); while (count == SIZE) { lock_release(&l); } count++; buffer[head] = c; head++; if (head == SIZE) { head = 0; char get() { char c; lock_acquire(&l); while (count == 0) { lock_release(&l); } count--; c = buffer[tail]; tail++; if (tail == SIZE) { tail = 0; return c; CS 140 Lecture Notes: Locks
4
CS 140 Lecture Notes: Locks
Producer/Consumer v3 char buffer[SIZE]; int count = 0; int head = 0, tail = 0; struct lock l; struct condition dataAvailable; struct condition spaceAvailable; lock_init(&l); cond_init(&dataAvailable); cond_init(&spaceAvailable); void put(char c) { lock_acquire(&l); while (count == SIZE) { cond_wait(&spaceAvailable, &l); } count++; buffer[head] = c; head++; if (head == SIZE) { head = 0; cond_signal(&dataAvailable, &l); lock_release(&l); char get() { char c; lock_acquire(&l); while (count == 0) { cond_wait(&dataAvailable, &l); } count--; c = buffer[tail]; tail++; if (tail == SIZE) { tail = 0; cond_signal(&spaceAvailable, &l); lock_release(&l); return c; T1 T2 T3 CS 140 Lecture Notes: Locks
5
CS 140 Lecture Notes: Locks
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.