Description:
I have multiple threads (4-32). These threads can all access an array: int resources[1024]. Resources array contains different values (0-1023). There can only be one instance of a single resource(int). Each thread requires different number of resources, which are at some point returned back to the array. Threads can ask for resources more than once and return only portion of acquired resources at once. Each thread is accessing this array via 2 methods: GetElement(), ReturnElement(int element)
GetElement(): this method locks section, deletes last element from resources array and returns it to the calling thread. Each thread is calling the method in loop for n resources.
ReturnElement(int element): this method locks section, appends resource element in parameter after last one in array. Each thread is calling the method in loop for n resources.
Current implementation is flawed in a way that when multiple threads are acquiring resources at once, none of them might get required amount. I was thinking about locking the access to the array for a single thread while it gets or returns the resources and then unlocking it. This approach is blocking all the other threads which might be an issue.
Is there a more efficient approach?