Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 257
mahonya Avatar asked Mar 01 '11 23:03

mahonya


2 Answers

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);}); 
        }
    };
like image 199
ronag Avatar answered Oct 12 '22 10:10

ronag


Check out boost.flyweight.

like image 38
ildjarn Avatar answered Oct 12 '22 08:10

ildjarn