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

3

8

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?

Culliton answered 1/3, 2011 at 23:18 Comment(0)
S
2

Check out boost.flyweight.

Slating answered 1/3, 2011 at 23:20 Comment(2)
is there any discussion on the boost docs on thread safety of flyweight ?Preponderant
@shrin : Whether or not Flyweight is thread-safe depends on the locking policy you specify.Slating
P
7

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);}); 
        }
    };
Promote answered 1/3, 2011 at 23:36 Comment(0)
S
2

Check out boost.flyweight.

Slating answered 1/3, 2011 at 23:20 Comment(2)
is there any discussion on the boost docs on thread safety of flyweight ?Preponderant
@shrin : Whether or not Flyweight is thread-safe depends on the locking policy you specify.Slating
W
1

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.

Whoremaster answered 23/11, 2016 at 9:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.