Ch.3 - IPC
Ch.3 - IPC
Critical Section
Problem
• The variable turn indicates whose turn it is to enter the critical section
• The flag array is used to indicate if a process is ready to enter the critical section.
flag[i] = true implies that process Pi is ready!
do {
do {
flag[i] = true; flag[j] = true;
turn = j; turn = i;
while (flag[j] && turn = = while (flag[i] && turn = = i);
j);
critical section
critical section flag[j] = false;
flag[i] = false; remainder section
remainder section } while (true);
} while (true);
} /* remainder section
*/
Returns the original value of
passed parameter } while (true);
signal(semaphore *S) {
S->value++;
if (S->value <= 0) {
remove a process P from S->list;
wakeup(P);
}
}
Code for producer process
Code for consumer process
The structure of the producer process
do {
...
/* produce an item in
next_produced */
...
wait(empty);
wait(mutex);
...
/* add next produced to
the buffer */
...
signal(mutex);
signal(full);
} while (true);
The structure of the consumer process
Do {
wait(full);
wait(mutex);
...
/* remove an item from buffer to next_consumed */
...
signal(mutex);
signal(empty);
...
/* consume the item in next consumed */
...
} while (true);
Readers-Writers Problem
• Readers – only read the data set; they do not perform any updates
• Writers – can both read and write
• Only one single writer can access the shared data at the same time
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-Writers
Problem (Cont.)
do {
wait(rw_mutex);
...
/* writing is performed
*/
...
signal(rw_mutex);
} while (true);
Readers-Writers
Problem (Cont.)
• The structure of a reader process
do {
wait(mutex);
read_count++;
if (read_count == 1)
wait(rw_mutex);
signal(mutex);
...
/* reading is performed */
...
wait(mutex);
read count--;
if (read_count == 0)
signal(rw_mutex);
signal(mutex);
} while (true);
Readers-Writers Problem Variations
• do {
Philosophe • // eat
• signal (chopstick[i] );