You are on page 1of 2

Question 1

Consider the following three threads:

// Th1 // Th2 // Th3

while (1) { while (1) { while (1) {


cout cout cout
<< "a"; << "b"; << "c";
} } }

These threads print a string containing any number of a's, b's and c's in any order. Synchronize
the threads (using Semaphores) so that the string becomes a concatenation of the substring "abc".
Following are few examples:

abc (correct)
abc abc (correct)
bac (incorrect)
abc cba (incorrect)
...

Question 2
Consider the following solution to the Barrier problem:

// shared variables
int n = ... ; // the number of threads
int count = 0;
Semaphore mutex = 1;
Semaphore barrier = 0;

// common code for threads


foo();

wait (mutex);
count = count + 1;
signal (mutex);

if (count == n)
signal (barrier);

wait (barrier);

bar();

Is this solution correct? Give a brief argument.


Question 3
Consider the following code for a simple Stack:

class Stack {
private:
int* a; // array for stack
int max; // max size of array
int top; // stack top
public:
Stack(int m) {
a = new int[m]; max = m; top = 0;
}
void push(int x) {
while (top == max)
; // if stack is full then wait
a[top] = x;
++top;
}
int pop() {
while (top == 0)
; // if stack is empty then wait
int tmp = top;
--top;
return a[tmp];
}
};

Assuming the functions push and pop can execute concurrently, synchronize the code using
semaphores. Also replace the busy waiting with proper waiting.

Question 4
Consider robots moving up and down a ladder. Assume the ladder is narrow and hence only one
robot can climb up or down at a time. However, multiple robots can move in one direction at the same
time.

Give pseudo-code for such a moving robot. Synchronize the climbing using semaphores. Do not
worry about starvation: assume the trains of robots are not very long.

Question 5
A barbershop consists of a waiting room with n chairs, and the barber room containing the
barber chair. If there are no customers to be served, the barber goes to sleep. If a customer enters the
barbershop and all chairs are occupied, then the customer leaves the shop. If the barber is busy, but
chairs are available, then the customer sits in one of the free chairs. If the barber is asleep, the customer
wakes up the barber. Write a program to coordinate the barber and the customers.

You might also like