Two more Problems
Notes
- Readers-Writers problem.
- The previous problem focused on preventing buffer overflow.
- In this case, there is a shared resource, like a table in a database
- You can either read from that table or write to it.
- Multiple readers can access at the same time
- But only one writer can access, and that must be exclusive access
- Multiple versions
- Version 1: No reader is kept waiting unless a writer has obtained a lock
- Version 2: Once a writer is ready to write, that must occur as soon as possible.
- We will examine a solution to version 1
- We need the following
- Semaphore: lockResource = 1
- This will provide a critical section for access to the resource
- It will be locked if there is a writer or at least one reader accessing the resource.
- Semaphore: readerCountMutex = 1
- This will provide a lock on readerCount
- Before a reader reads, they increment readerCount in a critical section.
- After they are done, they decrement readerCount, in a critical section.
- int readerCount = 0
- Writer:
Write: wait(lockResource) write to shared resource signal(lockResource) - Reader
Read: wait(readerCountMutex) ++readerCount if (readerCount == 1) wait(lockResource) signal (readerCountMutex) read wait(readerCountMutex) --readerCount if readerCount == 0 signal(lockResource) signal(readerCountMutex)
- Writer:
- The Dining Philosophers
- N > 1 (usually 4-5) philosophers, each brings one chopstick to the table.
- Philosophers either eat or think
- A philosopher requires two chopsticks to eat.
- They may only use the chopsticks to their left and right, they may not reach across another philosopher's plate.
- N > 1 (usually 4-5) philosophers, each brings one chopstick to the table.
- A bad solution
repeat think pick up left chopstick when it is available pick up right chopstick when it is available eat put down right chopstick put down left chopstick - There are multiple solutions
- Even-odd solution
- The philosophers put their chopstick to the right
- P1 c1 P2 c2 P3 c3 ... Pn cn
- P1 shares a chopstick with P2 and Pn
- Even philosophers pick up right chopstick first, then left
- Odd pick up left then right
- Say 2 and 3 want to eat,
- They will both try to pick up c2
- Assume P2 wins, then P3 will be stuck waiting for that chopstick and never hold c3
- So no matter what, P4 will be able to eat, and the chopsticks will eventually be released to that P2 will eventually be able to eat, put down c2 and P3 can then eat.
- The philosophers put their chopstick to the right
- Odd man out
- Everyone but p1 picks up to left, then right
- P1 must pick up right then left.
- By the same logic as above, we will not have deadlock.
- Even-odd solution
- Semaphore: lockResource = 1
- We need the following