并发对象池提供boost :: shared_ptr

|| 我想实现一个并发对象池,在该池中返回shared_ptr,而无需将其显式返回到池中。我基本上在并发队列中为其分配了一个推入shared_ptrs的数组,并实现了一个自定义删除器。似乎可以工作。我有什么想念的吗?
#ifndef CONCURRENTOBJECTPOOL_H
#define CONCURRENTOBJECTPOOL_H

#include <boost/shared_ptr.hpp>
#include <boost/shared_array.hpp>
#include <tbb/concurrent_queue.h>

namespace COP
{

template<typename T>
class ConcurrentObjectPool;

namespace 
{
template<typename T>
class ConcurrentObjectPoolDeletor
{
public:
  ConcurrentObjectPoolDeletor(ConcurrentObjectPool<T>& aConcurrentObjectPool): 
  _concurrentObjectPool(aConcurrentObjectPool) {}

  void operator()(T *p) const;

private:
  ConcurrentObjectPool<T>& _concurrentObjectPool;  
};
} // Anonymous namespace for ConcurrentObjectPoolDeletor

template <typename T>
class ConcurrentObjectPool
{
 public:
 ConcurrentObjectPool(const unsigned int aPoolSize)
   : _goingDown(false),
     _poolSize(aPoolSize), 
     _pool(new T[_poolSize]),
     _ConcurrentObjectPoolDeletor(*this)
  {
    for(unsigned int i = 0; i < _poolSize; ++i)
      {
        boost::shared_ptr<T> curr(&_pool[i], _ConcurrentObjectPoolDeletor);
        _objectQueue.push(curr);
      }
  }

  boost::shared_ptr<T> loan()
  {
    boost::shared_ptr<T> curr;
    _objectQueue.pop(curr);
    return curr;
  }

  ~ConcurrentObjectPool()
  {
    _goingDown = true;
    _objectQueue.clear();
  }

 private:
  void payBack(T * p)
  {
    if (! _goingDown)
      {
        boost::shared_ptr<T> curr(p, _ConcurrentObjectPoolDeletor);
        _objectQueue.push(curr);
      }
  }

  bool _goingDown;
  const unsigned int _poolSize; 
  const boost::shared_array<T> _pool;
  const ConcurrentObjectPoolDeletor<T> _ConcurrentObjectPoolDeletor;
  tbb::concurrent_bounded_queue<boost::shared_ptr<T> > _objectQueue;
  friend class ConcurrentObjectPoolDeletor<T>;
};

namespace
{
template<typename T>
void ConcurrentObjectPoolDeletor<T>::operator()(T *p) const
{
  _concurrentObjectPool.payBack(p);
}
} // Anonymous namespace for ConcurrentObjectPoolDeletor

} // Namespace COP

#endif // CONCURRENTOBJECTPOOL_H
    
已邀请:
        在设置
ConcurrentObjectPool
的析构函数中的
_goingDown
标志和读取
payBack()
中的标志之间存在竞争。它可能导致内存泄漏。 实际上,如果不尝试使析构函数安全地与ѭ3并发运行,可能会更好。无论如何,这都不安全,因为
_goingDown
标志是池对象的一部分,因此在池被销毁后对其进行访问将导致未定义的行为-即所有对象必须在销毁之前返回到池中。     
        看起来不错。您在使用时遇到任何问题吗?     

要回复问题请先登录注册