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?
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.
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?
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.
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()?