a) Below is a proposed solution to the Critical Section Problem (for 2 threads). [4 marks]
(Assume that two threads are launched with the id's 0 and 1)
int light[2]; light[0]=0; light[1]=0; // shared variables
int turn[2]; turn[0] =0; turn[1] =0;
void thread_function(int id) { // id is either 0 or 1
int j = 1 - id; // j is id of other thread
while(true) {
lights[id] = 1;
while((lights[j] == 1) && (turn[id] == 0)) {
turn[j] = 1; // tell other thread to go first
}
// --- perform critical section ---
turn[id] = 0;
lights[id] = 0;
}
}
Is this solution correct? Either provide a justification of why it is correct or give an example of how it fails one of the three requirements for the critical section problem.
Note: Do not worry about memory barriers, assume that memory transactions are performed
in order and are immediately visible to the other thread.
b) Provide a solution to the Critical Section Problem by writing implementations of [2 marks]
lock() and unlock() using the atomic instruction represented by the following pseudo code (note this is implemented as a single hardware instruction
that executes atomically.
int atomic_instruction(int *a, int e, int v) {
int o = *a;
if(o == e) {
*a = v;
}
return o;
}
c) Describe what would happen if a semaphore intended to be used for mutual [2 marks]
exclusion was initialised to 2 instead of 1?