Classical Problems of Synchronization
Classical Problems of Synchronization
1. Bounded-Buffer Problem
2. Readers and Writers Problem
3. Dining-Philosophers Problem
Bounded-Buffer Problem
Bounded-Buffer Problem
Two Process: Fixed Size Buffer
1. Producer
2. Consumer
The Consumer must not remove the data when the buffer is empty
Producer:
do { wait(S) {
while (S <= 0); // busy wait
wait(empty); //Decrease the Empty S--;
wait(mutex); //Acquire the lock }
...
//Insert Data into the Buffer
... signal(S) {
S++;
signal(mutex); //Release the lock }
signal(full); // Increase the Full
} while (true);
Consumer
do {
wait(full); // Decrease the full
wait(mutex); //Acquire the lock
...
/* Remove an item from the buffer
...
signal(mutex); // Release the lock
signal(empty); // Increase the empty
...
} while (true);
Readers and Writers Problem
Readers and Writers Problem
• A data set is shared among a number of concurrent processes
• Readers – only read the data set; they do not perform any updates
• Writers – can both read and write
• Several variations of how readers and writers are considered – all involve some form of priorities
• Shared Data
• Data set
• Semaphore rw_mutex initialized to 1
• Semaphore mutex initialized to 1
• Integer read_count initialized to 0
Readers and Writers Problem
signal(S) {
S++;
}
Reader:
wait(S) {
do { while (S <= 0); // busy
wait(mutex); wait
read_count++; S--;
if (read_count == 1) }
wait(rw_mutex);
signal(mutex);
... Writer Process:
/* reading is performed */ do {
... wait(rw_mutex);
wait(mutex); ...
read count--; /* writing is performed */
if (read_count == 0) ...
signal(rw_mutex); signal(rw_mutex);
signal(mutex); } while (true);
} while (true);
Dining-Philosophers Problem
// eat
signal (chopstick[i] );
signal (chopstick[ (i + 1) % 5] );
// think
} while (TRUE);
• Deadlock handling
• Allow at most 4 philosophers to be sitting
simultaneously at the table.
• Allow a philosopher to pick up the forks only if both
are available (picking must be done in a critical section.
• Use an asymmetric solution -- an odd-numbered
philosopher picks up first the left chopstick and then
the right chopstick. Even-numbered philosopher picks
up first the right chopstick and then the left chopstick.