Suppose there is a resource that can be used by upto 2 proce

Suppose there is a resource that can be used by upto 2 processes at a time. The method AccessResource provides access to this resource. To ensure that only two processes can access resource at a time, the processes are not allowed to call AccessResource directly. Instead, they call the function RequestResource which in turn allows them to access the resource.

The outline of RequestResource is as follows

RequestResource

{

              YOUR CODE

              AccessResource();

              YOUR CODE

}

Your task is to fill in the portion marked with `YOUR CODE\' so that only two processes can access the resource at a time even though more than two can request it at a time. (Note that what goes inside AccessResource is irrelevant to your assignment. Your job is to make sure that at most two of them can access it at a time)

Solve this problem using semaphores. This solution may not use busy waiting and has to guarantee fairness.

Solution

This solution should not use busy waiting which will waste CPU cycles. Hence if the process can\'t be given access to a resource, It should be queued up and blocked until we have room for another process to access. Once the resource is freed up, remove the process from queue and wake it up.

Let us assume there is a Semaphore check which is initialized with a value of 2 and declared in global scope. There is a Queue implementation QE with functions insert(processId) [which inserts the process identifier into the queue] and delete() [which remove a process identifier from queue and return it].

RequestResource()
{
check = check - 1;
if(check < 0)
{
QE.add(pid); pid - process id
block(); //Process will be blocked unless it is waken up by another process.
}
AccessResource();
check = check + 1;
if(check <= 0)
{
processId = QE.remove();
wakeup(processId); //Wake up the process which was blocked earlier
}
}

Suppose there is a resource that can be used by upto 2 processes at a time. The method AccessResource provides access to this resource. To ensure that only two

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site