是否有开源线程安全的C++对象池实现?

mah*_*nya 6 c++ thread-safety object-pooling

我需要创建一个套接字连接池,它将被提供给多个工作线程.是否有一个线程安全的对象池实现,其功能类似于Apache Commons GenericObjectPool

ron*_*nag 6

我通常使用TBB来实现线程安全的可伸缩池.

    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);}); 
        }
    };
Run Code Online (Sandbox Code Playgroud)


ild*_*arn 2

检查一下升压蝇量级