I am developing a function for a system where I firmly feel that there should be a template for this, which I should know about before diving into the code.
The scenario is this:
- I have a resource pool, of which I have a limited number.
- I have a variable number of consumers who use these resources; each consumer requires exactly one resource, and he may not use the same resource as any other consumer at a given time.
- Consumers are divided into a fixed number of groups, and the system must ensure that for each group there will be at least one resource.
- The number of consumers in each group varies over time; they are allocated and released as necessary.
My current approach is to load resources into two stacks when loading: one "crash stack" and one "shared stack." The emergency stack will contain as many resources as there are groups (for example, one for each group). The remaining available resources enter the common stack.
When a new consumer is created, the system will request a resource. If there are resources in the general stack, they will be deduced from them and returned to the caller. If the shared stack is empty, the resource can be unloaded from the emergency stack instead, but only if there are no consumers in the same group where the emergency resource already exists.
, , . , , , , .
, , , , : ? , .
. .