# Producer - Consumer

Document Sample

Today

• Dining Philosophers Problem
• Message Passing

1
Dining Philosophers

• Classic Synchronization Problem

• Philosopher
– eat, think, sleep
– eat, think, sleep
– ……..

• Philosopher = Process

• Eating needs two resources (chopsticks)
2
Problem: need
two chopsticks
to eat
3
First Pass at a Solution
One Mutex for each chopstick

Philosopher i:

while (1) {
Think();

lock(Left_Chopstick);
lock(Right_Chopstick);

Eat();

unlock(Left_Chopstick);
unlock(Right_Chopstick);
}

4
5
6

7
One Possible Solution

• Use a mutex for the whole dinner-table

• Philosopher i:
Performance
lock(table);       problem!
Eat();
Unlock(table);

8
Another Solution
Philosopher i:

Think();

unsuccessful = 1;
while (unsuccessful) {
lock(left_chopstick);
if (try_lock(right_chopstick)) /* try_lock returns immediately if
unable to grab the lock */
unsuccessful = 0;
else
unlock(left_chopstick);
}

Eat();                                             Problem: starvation if
unlock(left_chopstick);
unfavorable scheduling!
unlock(right_chopstick);

9
In Practice
• Starvation will probably not occur

• We can ensure this by adding
randomization to the system:
– Add a random delay before retrying
– Unlikely that our random delays will be in sync
too many times

10
Solution with Random Delays
Philosopher i:

Think();

while (unsuccessful) {
wait(random());

lock(left_chopstick);
if (trylock(right_chopstick))
unsuccessful = 0;
else
unlock(left_chopstick);
}

Eat();

unlock(left_chopstick);
unlock(right_chopstick);
11
Another Solution?

• Suppose two philosophers

• Philosopher 1:
lock(left_chopstick);
Q: Does this work?
lock(right_chopstick);
Does it for 3 philosophers?
• Philosopher 2:                        4 philosophers?
lock(right_chopstick);                5….?
lock(left_chopstick);

12
Yet Another Solution Idea
• Do not try to take forks one after another
– Don’t have each fork protected by a different
mutex

• Try to grab both forks at the same time

• Text has details

13

• Only one can be writing at any time
– When a writer is executing, nobody else can

• Performance Problems with naïve solution

• See more in the forthcoming labs

14
Message Passing

• No shared variables

• Two primitives:
– send (destination, message)
• Usually blocks till a message arrives
• Non-blocking version also usually available

15
Issues
• Across different machines,
message passing is the real thing

• Many issues to consider:
– Marshaling data into messages
– Provide reliable transmission across unreliable links?
– Event-driven mode of programming

• Computer Networking:
deals with sending messages across networks

16

DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
 views: 3 posted: 2/18/2012 language: English pages: 16
How are you planning on using Docstoc?