You are on page 1of 4

Exercise

EXERCISE 1
Process P:

while (true) {

waitForNewRequest();

if(found){

hit+=1;

val=hit;

Respond();

hit: a global variable

Given the above code, identify the critical section of the code and solve the problem with semaphore.

Suppose hit=100, run the code (with semaphore) with 2 instances of P, i.e., P1, P2, P1. When P1 runs
hit+=1; then P1 runs out of time, and P2 also wants to run hit+=1; Run step by step for P1 and P2

Solution:

while (true) {

waitForNewRequest();

if(found){

hit+=1; //Critical section

val=hit; //Critical section

Respond();

}
With semaphore:

while (true) {

if(found){

wait(mutex);

hit+=1;

val=hit;

signal(mutex);

P1:

wait(mutex) => mutex = 0

hit += 1 => hit = 101 P2:

wait(mutex) => mutex = -1 => waiting

waiting

val = hit => val = 101 waiting

signal(mutex) => mutex = 0 hit += 1 => hit = 102

val = hit => val = 102

signal(mutex) => mutex = 1

P1

wait(mutex) => mutex = 0

hit += 1 => hit = 103

val = hit => val = 103

signal(mutex) => mutex = 1

2
EXERCISE 2

Given the Write/Reader

Suppose the total slots in the buffer is 10. There are three processes Reader 1 (R1), Reader 2 (R2) and
Writer (W).

Run steps by steps of the three processes with following order: R1, R2, W, W, R1

Mutex=1; empty=10; full=0;

R1: Wait(full), full=0 -> block(R1)

R2: Wait(full), full=0 -> block(R2)

W: Wait(empty) -> empty=9

Wait(mutex) -> mutex=0

Write

Signal(mutex) -> mutex=1

Signal(full) -> full=1

W: Wait(empty) -> empty=8

Wait(mutex) -> mutex=0

Write

3
Signal(mutex) -> mutex=1

Signal(full) -> full=2

R1: Wait(full) -> full=1

Wait(mutex) -> mutex=0

Read

Signal(mutex) -> mutex=1

Signal(empty) -> empty=9

You might also like