We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 1 year ago.
Improve this questionI need to create a pool of socket connections which will be served to multiple worker threads. Is there a thread safe object pool implementation with functionality similar to Apache Commons' GenericObjectPool
开发者_StackOverflow?
I usually use TBB to implement thread-safe scalable pools.
template <typename T>
class object_pool
{
std::shared_ptr<tbb::concurrent_bounded_queue<std::shared_ptr<T>>> pool_;
public:
object_pool()
: pool_(new tbb::concurrent_bounded_queue<std::shared_ptr<T>>()){}
// Create overloads with different amount of templated parameters.
std::shared_ptr<T> create()
{
std::shared_ptr<T> obj;
if(!pool_->try_pop(obj))
obj = std::make_shared<T>();
// Automatically collects obj.
return std::shared_ptr<T>(obj.get(), [=](T*){pool_->push(obj);});
}
};
Check out boost.flyweight.
The best ready-to-use implementation I've found so far is the one in Poco (Portable Components - neat C++ framework).
There is a class Poco::ObjectPool
- see the documentation here. You can customize it in several ways providing your own factory which creates, validates, deactivates and destroys objects.
Also strangely at the time of writing this answer their site contains not the latest generated doc - my latest Poco source has a newer version with some new functionality, e.g. there is a timeout parameter for borrowObject()
now which was critical for me.
精彩评论