Semaphore put method question

hI

I have a question regarding semaphore.

code


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
  task automatic display(string str);
  sema.get();
  $display("%s",str);
  sema.put();
  sema.put();
  endtask

endmodule


My question is if we use put two times, does the task get stuck because by definition put method is blocking or it actually increases the number of keys to 2 when you use an extra put and it does not behave as blocking?

In reply to Himanshu Madnani:

put() is a function, it cannot block.

Your example constructs the semaphore with four keys. Each process grabs one key and returns two keys. At the end, there are eight keys and nothing ever blocked.

Hi,

If there is only one process, e.g. “process1”, and it calls get() twice, without a put() in between the get() calls. Then does the process1 get blocked the on the second call, if it got the semaphore on the first call?

Another scenario, is if there are two processes, and say process1 has got the semaphore and not released it. Is there a way for for process2 to determine which process has the semaphore? I mean can it determine the name of the process? Process2 using try_get() will only determine if it gets the semaphore or not, but is there a way for it to determine which other process has hold of the semaphore?

Thanks,

Preethi

If a semaphore is created with 4 keys, and there are no other put() calls, the get(1) method can be called 4 times before getting blocked.

Semaphores are fundamental locking mechanisms used to control access to shared resources. To manage the number of keys and determine which process holds them, you must write code around semaphores. Several methods exist to identify the process with the keys. Each process can set a flag to indicate possession of the keys. However, when dealing with concurrent processes, it can lead to race conditions between testing the flags and setting them. Additionally, situations like starvation and deadlock may occur, based on the actual situation at hand.

Many Thanks Dave for this information.

If the semaphore is created with 1 key and if the same process calls the get(1) method twice, without an put() after the first get(), then does that process block on the second get()?

It is simple.