问题
I 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
?
回答1:
Check out boost.flyweight.
回答2:
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);});
}
};
回答3:
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.
来源:https://stackoverflow.com/questions/5161614/is-there-an-open-source-thread-safe-c-object-pool-implementation