1

shared_ptr が返され、明示的にプールに返す必要がない同時オブジェクト プールを実装したかったのです。私は基本的に、並列キューに配列を割り当て、shared_ptrs をプッシュし、カスタム deletor を実装しました。うまくいくようです。何か不足していますか?

#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
4

2 に答える 2

2

_goingDownのデストラクタでフラグを設定するConcurrentObjectPoolことと、 でフラグを読み取ることの間に競合がありpayBack()ます。メモリ リークが発生する可能性があります。

実際には、デストラクタを同時に実行しても安全にしようとしない方が良いかもしれませんpayBack()。とにかく安全ではありません。_goingDownフラグがプール オブジェクトの一部であり、プールが破棄された後にフラグにアクセスすると、未定義の動作が発生するためです。つまり、すべてのオブジェクトは、破棄される前にプールに戻される必要があります。

于 2011-06-14T20:54:00.850 に答える
0

いいね。使用中に問題が発生していますか?

于 2011-06-14T07:53:49.000 に答える