The semaphore in the Golang is implemented with the channel:
An example is the following:
https://sites.google.com/site/gopatterns/concurrency/semaphores
Context:
We have several hundred servers, and there are common resources to which we want to restrict access. Therefore, for this resource we want to use a semaphore to restrict access to only 5 simultaneous accesses of these servers. For this, we plan to use a lock server. When a computer accesses a resource, it first registers with the lock server that it is accessing the resource using a key. And then, when this is done, he will send another request to the lock server to say that it is done and release the semaphore. This ensures that we restrict access to these resources to the maximum amount of simultaneous access.
Problem: Want to handle it gracefully if something goes wrong.
Question
How are you going to implement a timeout on a semaphore?
Example:
Let's say I have a semaphore of size 5. There are 10 processes at the same time trying to get a lock in the semaphore, so in this case only 5 will get it.
Sometimes processes die without reacting (the real reason is a little complicated to explain, but basically sometimes the process may not unlock it), which causes a problem, since the space in the semaphore is now permanently locked.
So, I would like to have a timeout on this. Here are some issues:
Processes will be performed anywhere from 2 seconds to 60 minutes.
We have some conditions for the race, because if time runs out, and then the process tries to unlock it, we unlock the semaphore twice, and not once. And vice versa, we first open it, and then iterate over.
How to take the proposed template published above and turn it into a thread-safe semaphore with timeouts?