I tried the below sample program to understand semaphores better.
At time 45 both process-1 and process-2 get the keys at the same time.
Is this because the PUT corresponding to try_get added a key to the pool even though it did not get a key ?
semaphore sema; //declaring semaphore sema
initial begin
sema=new(1); //creating sema with '1' key
fork
display(1); //process-1
display(2); //process-2
// display(3); //process-2
join
end
//display method
task automatic display(int id);
bit success = 0;
success = sema.try_get(); //getting '1' key from sema
$display($time,"\tTRY_GET KEY for ID = %0d, success = %0d, Simulation Time", id, success);
#30;
sema.put(); //putting '1' key to sema
$display($time,"\tPUT KEY TRY for ID = %0d, Simulation Time", id);
sema.get();
$display($time,"\tGET KEY for ID = %0d, Simulation Time", id);
#15;
sema.put();
$display($time,"\tPUT KEY for ID = %0d, Simulation Time", id);
endtask
endmodule
Output:
0 TRY_GET KEY for ID = 1, success = 1, Simulation Time
0 TRY_GET KEY for ID = 2, success = 0, Simulation Time
30 PUT KEY TRY for ID = 1, Simulation Time
30 GET KEY for ID = 1, Simulation Time
30 PUT KEY TRY for ID = 2, Simulation Time
30 GET KEY for ID = 2, Simulation Time
45 PUT KEY for ID = 1, Simulation Time
45 PUT KEY for ID = 2, Simulation Time