You are on page 1of 3

CS 330: Operating System

Assignment 2
BESE 23 (A & C)

Solution

1. In the candy shop, a customer enters and takes a number (the number is incremented every
time a new customer enters). Some number of sales people (e.g. N) waits on them in order of
their arrival.
If a sales person is free when the customer takes a number, the sales person waits on the
customer right away.
If no sales person is free when the customer takes a number, the customer waits.

Enter routine is called when any customer enters the shop.


Finish routine is called before the customer leaves the shop.

Use the following:


int ticket;
Semaphore mutex; // control access to shared variables
Semaphore servers; // count of Sales people

 What will be the initial values of the semaphores?


 Write Enter and Finish routines for the customers.

int ticket;
Semaphore mutex = 1; // control access to shared variables
Semaphore servers = N; // Sales people

Enter( ) Finish( )
{ {
wait (mutex); signal (servers);
ticket ++; }
signal(mutex);

wait (servers);
}

1
2. Explain and justify whether this code solves the Critical Section problem for two processes.
// Initialization
Boolean flag[2];
flag [0] = FALSE;
flag [1] = FALSE;

// Process i
while (TRUE)
{
while (flag[(i+1)%2] == TRUE) ; 1
flag [i] = TRUE; 2
<< critical section >> 3
flag[i] = FALSE; 4
}

Consider P0 preempts after line 1, before setting its flag to TRUE at line 2.
If P1 executes line 1, the condition will be FALSE and it will enter the critical section after setting
its flag=TRUE.
Now if P0 resumes from line 2, it will set its flag=TRUE and will also enter the critical section.
Therefore, Mutual Exclusion is not maintained and this code does not solve the Critical Section
problem.

2
3. Consider a coke machine that has 10 slots. The delivery person adds coke cans in the machine
whenever there are available slots. The student can get in the queue and can take coke.

We can use the following three semaphores:


semaphore mutex /* for mutual exclusion */
semaphore filledSlots /* Number of filled slots */
semaphore emptySlots /* Number of empty slots */

 Identify the critical section of the code.


 Generate code for delivery person and student that guarantee mutual exclusion.

semaphore mutex = 1

semaphore fullBuffer = 0

semaphore emptyBuffer = 10

delivery_person( ) { student( ) {

wait(emptyBuffer) wait(fullBuffer);
wait(mutex) wait(mutex);
<<put_1_coke_in_machine>> <<take_1_coke_from_machine>>
signal(mutex)
signal(mutex)
signal(fullBuffer)
signal(emptyBuffer)
}
}

You might also like