boost::lockfree - 为排队元素调用析构函数

boost::lockfree - Call destructor for queued element

我无法强制销毁 pop 上的 boost::lockfree::spsc_queue 元素。 (当推送覆盖循环缓冲区的元素或列表被销毁时,即使通过引用访问元素,它们也会被正确销毁)。

我也无法直接访问存储在队列中的元素以通过引用销毁它。

#include <boost/lockfree/spsc_queue.hpp>
#include <boost/lockfree/policies.hpp>
#include <iostream>
#include <memory>

using namespace boost::lockfree;

class testDestructor{
        public:
        int x;
        static int y;
        testDestructor(): x(y++){}
        ~testDestructor(){ std::cout << x << std::endl ;}
        };

int testDestructor::y=1;


spsc_queue< std::shared_ptr<testDestructor>, capacity<100>> q;
int sum = 0;

void produce()
{
  for (int i = 1; i <= 100; ++i)
    q.push( std::move( std::shared_ptr<testDestructor>( new testDestructor() ) ) ) ;
}


void consume( std::shared_ptr<testDestructor> & tp){
    sum+=tp->x;
//TRYING TO FORCE DESTRUCTION:
    tp.reset();
}

int main()
{
  produce();
  //consuming a reference to force freeing the pointer
  q.consume_all([](  std::shared_ptr<testDestructor>  & tp){ consume(tp);  });
  std::cout << sum << "<- Destructors should be called before this" << std::endl;
}

旧版本的 boost 中 spsc_queue 存在一些问题。您发布的代码适用于 boost 1.60。如果可以,请升级到当前版本。

在 Coliru 直播