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

99封情书 提交于 2019-12-03 14:35:09

Check out boost.flyweight.

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);}); 
        }
    };

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!