A synchronization mechanism consists of 2 atomic routines, ENQ(r) and DEQ(r) \"r
ID: 3865903 • Letter: A
Question
A synchronization mechanism consists of 2 atomic routines, ENQ(r) and DEQ(r) "r" is a resource variable that has two fields, inuse (boolean) and queue (a queue) which is a queue of processes waiting to acquire the resource. The definitions of ENQ and DEQ are: ENQ(r): if (r.inuse == 1) then begin insert current process in r.queue block end else r.inuse = 1: DEQ(r): if r.queue == nil then inuse = false else delete a process from r.queue and activate it. Construct an implementation of ENQ/DEQ using semaphores. You can use other variables, etc that you need, but no other atomic code or synchronization constructs other than P or V can be used. Do the reverse of Q3, that is implement Semaphores using ENQ/DEQ.Explanation / Answer
Answer:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
ENQUEUE:
ENQ (r, item)
{
acquire(mutex);
put the item into the queue of the variable r;
release(mutex);
}
//Class
Class QueueList
{
//Declare the needed variables
Data* header, trailer;
Semaphore mutex;
//Constructor
void QueueList()
{
//Initialize
header = trailer = NULL;
//Initialize
mutex=1;
}
//Method definition ENQ(r)
void ENQ(int r)
{
//Declare variable
Data* d;
//Add
d = new Data(r);
//Call P
P(mutex);
//Check condition
if (header==NULL)
//Update
header=d;
//Otherwise
else
//Update trailer next
trailer->next=d;
//Update trailer
trailer=d;
//Call V
V(mutex);
}
DEQUEUE:
DEQ(r)
{
acquire(mutex);
pick up an item from the queue of the variable r.
release(mutex);
return item;
}
//Method definition DEQ()
int DEQ()
{
//Declare the needed variables
Data* d;
int v;
P(mutex);
d=header;
//Check condition
if (d==NULL)
{
//Call V
V(mutex);
//Return
return -1;
}
//Check condition
if (d==trailer) trailer=NULL;
//Update header
header=d->next;
//Call V
V(mutex);
//Update
v=d->value;
//Delete
delete d;
//Return
return v;
}
}
Second Method:
Answer (3):
Considering the fact that semaphores are used for shared resources and limit the usage.
Only one can acquire the resource , thus it has to be initialized by 1.
One operation, V, adds 1 to the natural and the other operation, P, decreases the natural number by 1.
p(r) = Enq(r ) as number is getting reduced ( usage increased)
whereas v(r) = Dec (r ) as number is getting added ( usage decreased)
The resource is a Semaphore initialized to 1
P(r) = Enq(r)
V(r) = DEQ(r)
ENQ(r):
P(r)
if(r.inuse==1) then begin
Insert current process in r.queue
V(r)
Block
End
Else
P(r )
r.inuse=1;
V(r )
DEQ(r):
P( r)
if r.queue=nil then inuse=false
V(r )
Else
P(r )
delete a process from r.queue and activate it.
V( r)
Answer (4):
P (r)
If(r.inuse==1) then begin
ENQ( r)
Block
End
V( r)
If(r.queue=nil then inuse=false
Else
DEQ( r)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.