Is there an open source thread safe C++ object pool implementation?

4.6k views Asked by At

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?

3

There are 3 answers

2
ildjarn On BEST ANSWER

Check out boost.flyweight.

0
ronag On

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);}); 
        }
    };
0
Roman Kruglov On

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.