module semaphore_ex;
semaphore sema; //declaring semaphore sema
initial begin
sema=new(4); //creating sema with '4' keys
fork
display("Process 1"); //process-1
display("Process 2"); //process-2
display("Process 3"); //process-3
display("Process 4"); //process-4
join
end
//display method
task automatic display(string msg);
sema.get(2); //getting '2' keys from sema
$display($time,"\tGot the key for %s",msg);
// else
// $display("\t No key ");
#30;
sema.put(2); //putting '2' keys to sema
$display($time,"\tPutting back the key by %s",msg);
endtask
endmodule
RESULT: for sema.get(2)
0 Got the key for Process 1
0 Got the key for Process 2
30 Putting back the key by Process 1
30 Putting back the key by Process 2
30 Got the key for Process 3
30 Got the key for Process 4
60 Putting back the key by Process 3
60 Putting back the key by Process 4
V C S S i m u l a t i o n R e p o r t
THis is the result when you use sema.get(2), But when we run the same program with sema.get(3). The processes 1,2 and 3 are expected to run simultaneously but we get a different result. Why is that?
RESULT: For sema.get(3)
0 Got the key for Process 1
30 Putting back the key by Process 1
30 Got the key for Process 2
60 Putting back the key by Process 2
60 Got the key for Process 3
90 Putting back the key by Process 3
90 Got the key for Process 4
120 Putting back the key by Process 4
V C S S i m u l a t i o n R e p o r t
Is there a way to know the number of keys available which are not being used?
Or to know how many keys are remaining and can be used for other processes to be used?