implement a resource pool in C++
时间: 2024-04-13 17:29:18 浏览: 128
To implement a resource pool in C++, you can use a combination of data structures and synchronization mechanisms. Here's a simple example:
```cpp
#include <iostream>
#include <queue>
#include <mutex>
#include <condition_variable>
template<typename T>
class ResourcePool {
public:
ResourcePool(size_t maxSize) : max_size(maxSize), available_resources(0) {}
T acquire() {
std::unique_lock<std::mutex> lock(mutex);
while (resources.empty()) {
if (available_resources >= max_size) {
// Wait until a resource is released
cv.wait(lock);
} else {
// Create a new resource if the pool is not full
resources.push(createResource());
++available_resources;
}
}
T resource = resources.front();
resources.pop();
return resource;
}
void release(T resource) {
std::lock_guard<std::mutex> lock(mutex);
resources.push(resource);
cv.notify_one();
}
private:
size_t max_size;
size_t available_resources;
std::queue<T> resources;
std::mutex mutex;
std::condition_variable cv;
// Create a new resource object (replace with your own code)
T createResource() {
return T();
}
};
// Example usage
class MyResource {
public:
void use() {
std::cout << "Using resource" << std::endl;
}
};
int main() {
ResourcePool<MyResource> pool(5);
// Acquire and use resources
for (int i = 0; i < 10; ++i) {
MyResource* resource = pool.acquire();
resource->use();
pool.release(resource);
}
return 0;
}
```
In this example, `ResourcePool` is a template class that manages a pool of resources of type `T`. The pool has a maximum size specified during construction. The `acquire` function is used to obtain a resource from the pool, and the `release` function is used to return a resource to the pool.
The pool uses a queue to store the available resources. When a resource is acquired, it is removed from the queue. If no resources are available, the acquiring thread waits until a resource is released.
Remember to replace the `createResource` function with your own code that creates and initializes a new resource object of type `T`.
阅读全文